Exception Handling in Python
Prof. Dr. Matangini Chattopadhyay
School of Education Technology
Jadavpur University
What is exception?
• When an error (i.e., runtime error) occurs,
Python will normally stop and generate an
error message. These errors are called
exceptions.
• These exceptions can be handled using four
keywords:
– The try block lets you test a block of code for errors.
– The except block lets you handle the error.
– The else block lets you execute code when there is no
error.
– The finally block lets you execute code, regardless of the
result of the try and except blocks.
Example
try:
print(x)
except:
print("An exception occurred") # An exception
# occurred
Without the try block, the program will crash and
raise an error.
print(x)
Traceback (most recent call last):
File "./[Link]", line 1, in <module>
NameError: name 'x' is not defined
Many Exceptions
Print one message if the try block raises
a NameError and another for other errors.
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Output:
Variable x is not defined
else keyword
• Use the else keyword to define a block of code to
be executed if no errors are raised.
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Output:
Hello
Nothing went wrong
finally keyword
• The finally block, if specified, will be executed regardless if the
try block raises an error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Output:
Something went wrong
The 'try except' is finished
Note: This can be useful to close objects and clean up resources.
Finally: Example
• Try to open and write to a file that is not writable.
try:
f = open("[Link]")
try:
[Link](“Hello, World!")
except:
print("Something went wrong when writing to the file")
finally:
[Link]()
except:
print("Something went wrong when opening the file")
# Something went wrong when writing to the file
Raise an exception
•To throw (or raise) an exception, use the raise keyword.
Example: Raise an error and stop the program if x is less than 0.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Output:
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
Raise an exception (Contd.)
• You can define what kind of error to raise, and the text to print to the
user.
Example: Raise a TypeError if x is not an integer.
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Output:
Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed