Exception Handling in Python
Exception Handling in Python
1 Exception handling
It is a mechanism in programming to handle runtime errors, which are known as exceptions.
It’s a process where you define a block of code that will be executed if an error occurs when the
program is running. This allows the program to continue running (or terminate gracefully) even if
an error occurs.
Without exception handling, an error occurring in a program would cause the program to immedi-
ately stop. This can be very undesirable, especially in production software, as it can lead to a poor
user experience or even data loss.
In Python, you use try and except blocks. The try block contains the code that might raise an
exception, and the except block contains the code that will be executed if an exception is raised.
The else block allows you run code without errors.
The finally block executes code regardless of the try-and-except blocks.
Some of the most common types of exceptions are:
ZeroDivisionError: Raised when the second argument of a division or modulo operation is zero.
TypeError: Raised when an operation or function is applied to an object of inappropriate type.
ValueError: Raised when a built-in operation or function receives an argument that has the right
type but an inappropriate value.
IndexError: Raised when a sequence subscript is out of range.
KeyError: Raised when a dictionary key is not found.
FileNotFoundError: Raised when a file or directory is requested but doesn’t exist.
IOError: Raised when an I/O operation (such as a print statement, the built-in open() function or
a method of a file object) fails for an I/O-related reason.
ImportError: Raised when an import statement fails to find the module definition or when a from
… import fails to find a name that is to be imported.
MemoryError: Raised when an operation runs out of memory.
OverflowError: Raised when the result of an arithmetic operation is too large to be expressed by
the normal number format.
AttributeError: Raised when an attribute reference or assignment fails.
1
SyntaxError: Raised when the parser encounters a syntax error.
IndentationError: Raised when there is incorrect indentation.
NameError: Raised when a local or global name is not found.
Role of Try and Except:
try block: The code within the try block contains the statements that may potentially raise an
exception. It allows you to specify the section of code that you want to monitor for exceptions.
except block: If an exception occurs within the try block, the corresponding except block(s) are
executed. The except block allows you to define the actions or code that should be executed when
a specific exception is raised. You can have multiple except blocks to handle different types of
exceptions.
The else block allows you run code without errors.
The finally block executes code regardless of the try-and-except blocks.
Use the raise keyword to throw (or raise) an exception.
try:
x = 2
print(x)
except:
print("There is no X")
finally:
print("The 'try except' executed")
2
2
The 'try except' executed
x = 2
if x < 10:
raise Exception("There is a problem: X is below zero")
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
Cell In[6], line 6
3 x = 2
5 if x < 10:
----> 6 raise Exception("There is a problem: X is below zero")
2 ZeroDivisionError
[7]: n = int(input("Please enter the numerator: "))
d = int(input("Please enter the denominator: "))
result = n / d
print("Result:", result)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[7], line 4
1 n = int(input("Please enter the numerator: "))
2 d = int(input("Please enter the denominator: "))
----> 4 result = n / d
5 print("Result:", result)
[8]: try:
n = int(input("Please enter the numerator: "))
d = int(input("Please enter the denominator: "))
result = n / d
3
print("Result:", result)
except ZeroDivisionError:
print("There is an Error: Division by zero is not allowed.")
3 ValueError
[9]: """Raised when a built-in operation or function receives an
argument that has the right type but an inappropriate value."""
result = n / d
print("Result:", result)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[9], line 5
1 """Raised when a built-in operation or function receives an
2 argument that has the right type but an inappropriate value."""
4 n = int(input("Please enter the numerator: "))
----> 5 d = int(input("Please enter the denominator: "))
7 result = n / d
8 print("Result:", result)
[10]: try:
n = int(input("Please enter the numerator: "))
d = int(input("Please enter the denominator: "))
result = n / d
print("Result:", result)
except ValueError:
print("Please enter valid integers for the numerator and denominator.")
4
Please enter valid integers for the numerator and denominator.
try:
n = int(input("Please enter the numerator: "))
d = int(input("Please enter the denominator: "))
result = n / d
print("Result:", result)
except ValueError:
print("Please enter valid integers for the numerator and denominator.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
4 TypeError
[12]: try:
x = "10" # Assigning a string value to the variable x
y = 2
print("Result:", z)
except TypeError:
print("Error: TypeError occurred.")
5 IndexError
[13]: try:
list1 = [1, 2, 3]
except IndexError:
print("IndexError error occurred.")
5
6 KeyError
[14]: try:
my_dictionary = {"name": "John", "age": 30}
except KeyError:
print("KeyError error occurred.")
7 FileNotFoundError
[15]: try:
file_location = "my_file.txt"
except FileNotFoundError:
print(f"File '{file_path}' not found.")
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[15], line 4
1 try:
2 file_location = "my_file.txt"
----> 4 with open(file_path, "r") as file:
5 contents = file.read()
7 except FileNotFoundError:
8 IOError
[1]: try:
file_location = "file123.txt"
except IOError:
print(f"Unable to write to file '{file_location}'.")
6
9 ImportError
[17]: try:
import library1234
except ImportError:
print("Unsuccessful to import module 'library1234'.")
10 MemoryError
[18]: # Creating a large list that consumes a
# significant amount of memory
try:
large_list = [1] * (10 ** 12)
except MemoryError:
print("Insufficient memory for the list.")
11 OverflowError
[9]: """"Raised when the result of an arithmetic operation is too large
to be expressed by the normal number format."""
try:
result = 500000 ** 1000 # Attempting to calculate an extremely large number
except ValueError:
print("Error: Calculation resulted in an overflow.")
else:
print(result)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[9], line 9
7 print("Error: Calculation resulted in an overflow.")
8 else:
----> 9 print(result)
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use␣
↪sys.set_int_max_str_digits() to increase the limit
7
12 AttributeError
[20]: try:
age = 20
except OverflowError:
print("'age' object has no attribute.")
else:
print(result)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[20], line 6
3 age = 20
5 # Using append method
----> 6 age.append(12)
8 except OverflowError:
9 print("'age' object has no attribute.")
13 SyntaxError
[21]: try:
print("John age is:"
age = 20
except SyntaxError:
print("Error: Invalid syntax.")
8
14 IndentationError
[22]: try:
name = "John"
age = 50
except IndentationError:
print("There is an IndentationError")
15 NameError
[23]: try:
side = "4"
print(area) # Attempting to access an undefined variable
except NameError:
print("NameError is there")
NameError is there
Here’s a brief description of each exception:
BaseException: The base class for all built-in exceptions.
Exception: The base class for all non-exit exceptions.
ArithmeticError: Raised for any arithmetic errors.
BufferError: Raised when operations on a buffer are not possible.
LookupError: Raised when a mapping (dictionary) key or sequence index is not found.
AssertionError: Raised when an assert statement fails.
AttributeError: Raised when attribute reference or assignment fails.
EOFError: Raised when the input() function hits an end-of-file condition (EOF).
FloatingPointError: Raised when a floating point operation fails.
GeneratorExit: Raised when a generator or coroutine is closed.
ImportError: Raised when the import statement fails to find the module definition.
ModuleNotFoundError: A subclass of ImportError, raised when an import statement fails to find
the module.
9
IndexError: Raised when a sequence subscript (index) is out of range.
KeyError: Raised when a dictionary key is not found.
KeyboardInterrupt: Raised when the user interrupts program execution (usually by pressing
Ctrl+C).
MemoryError: Raised when an operation runs out of memory.
NameError: Raised when a local or global name is not found.
NotImplementedError: Raised when an abstract method requiring an override in an inherited class
is not provided.
OSError: Raised when a system-related error occurs.
OverflowError: Raised when the result of an arithmetic operation is too large to be expressed.
RecursionError: Raised when the maximum recursion depth has been exceeded.
ReferenceError: Raised when a weak reference proxy is used to access a garbage collected referent.
RuntimeError: Raised when an error is detected that doesn’t fall in any of the other categories.
StopIteration: Raised by built-in function next() and an iterator‘s next() method to signal that
there are no further items.
StopAsyncIteration: Raised by an asynchronous iterator object’s anext() method to stop the
iteration.
SyntaxError: Raised by the parser when a syntax error is encountered.
IndentationError: Raised when there is incorrect indentation.
TabError: Raised when indentation contains mixed tabs and spaces.
SystemError: Raised when the interpreter finds an internal problem.
SystemExit: Raised by the sys.exit() function.
TypeError: Raised when an operation or function is applied to an object of inappropriate type.
UnboundLocalError: Raised when a local variable is referenced before it has been assigned a value.
UnicodeError: Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError: Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError: Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError: Raised when a Unicode-related error occurs during translating.
ValueError: Raised when a built-in operation or function receives an argument that has the right
type but an inappropriate value.
ZeroDivisionError: Raised when the second argument of a division or modulo operation is zero.
EnvironmentError: Base class for exceptions that can occur outside the Python system.
IOError: Raised when an I/O operation (such as a print statement, the built-in open() function or
a method of a file object)
10
[24]: def quiz_on_exception():
# Quiz Questions
quiz_data = [
{
"question": "Which keyword is used for exception handling?",
"options": ['a) raise', 'b) try', 'c) handle', 'd) exception'],
"answer": 'b'
},
{
"question": "What is the purpose of the 'finally' clause in Python␣
↪exception handling?",
↪above'],
"answer": 'a'
},
{
"question": "Which built-in exception is raised when a function or␣
↪operation is not implemented yet?",
"answer": 'a'
},
{
"question": "Which of the following exceptions is NOT raised by␣
↪Python built-in operations?",
"answer": 'c'
},
{
"question": "What exception is raised when a local or global name␣
↪is not found?",
"answer": 'd'
},
{
"question": "What exception is raised when the parser encounters a␣
↪syntax error?",
"answer": 'b'
},
{
11
"question": "What exception is raised when there is incorrect␣
↪indentation?",
"options": ['a) IndentationError', 'b) ValueError', 'c)␣
↪SyntaxError', 'd) TypeError'],
"answer": 'a'
},
{
"question": "What exception is raised when an operation or function␣
↪receives an argument of the right type but an inappropriate value?",
"answer": 'a'
},
{
"question": "What exception is raised when a sequence subscript is␣
↪out of range?",
"answer": 'd'
},
{
"question": "What exception is raised when an import statement␣
↪fails to find the module definition or when a from ... import fails to find␣
"answer": 'a'
},
{
"question": "What exception is raised when an operation runs out of␣
↪memory?",
"answer": 'a'
},
{
"question": "What exception is raised when the result of an␣
↪arithmetic operation is too large to be expressed by the normal number␣
↪format?",
"answer": 'a'
},
{
"question": "What exception is raised when an attribute reference␣
↪or assignment fails?",
12
"options": ['a) AttributeError', 'b) KeyError', 'c) ImportError',␣
↪'d) NameError'],
"answer": 'a'
},
{
"question": "What exception is raised when a file or directory is␣
↪requested but doesn’t exist?",
"answer": 'a'
},
{
"question": "What exception is raised when a dictionary key is not␣
↪found?",
"answer": 'a'
},
]
def ask_question(question_data):
print(question_data["question"])
for option in question_data["options"]:
print(option)
while True:
try:
user_answer = input("Enter your answer: ")
if user_answer in ['a', 'b', 'c', 'd']:
correct = user_answer == question_data["answer"]
if not correct:
print(f"Incorrect.")
return user_answer, question_data["answer"], correct
else:
raise ValueError("Invalid option. Please enter a, b, c, or␣
↪d.")
except ValueError as e:
print(e)
score = 0
all_answers = [] # a list to store all the user's answers and correct␣
↪answers
13
if correct:
print("Correct!")
score += 1
print("\n"+"-"*30+"\nQuiz Results\n"+"-"*30)
for item in all_answers:
print(f"Question: {item[0]}\nYour Answer: {item[1]}\nCorrect Answer:␣
↪{item[2]}\n{'Correct' if item[3] else 'Incorrect'}")
print("-"*30)
print(f"You scored {score}/{len(quiz_data)}.")
[ ]: quiz_on_exception() # run this and solve the basic quiz for the exception␣
↪handling
14