Python Exception Handling Using try, except and finally statement
1. Python has many built-in exceptions that are raised when your program
encounters an error (something in the program goes wrong).
2. When these exceptions occur, the Python interpreter stops the current
process and passes it to the calling process until it is handled.
3. If not handled, the program will terminate in between the execution.
Catching Exceptions in Python
1. In Python, exceptions can be handled using a try statement.
2. The critical operation which can raise an exception is placed inside the try
clause.
3. The code that handles the exceptions is written in the except clause.
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
Since every exception in Python inherits from the base Exception class,
we can also perform the above task in the following way:
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except Exception as e:
print("Oops!", e.__class__, "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
Catching Specific Exceptions in Python
1. In the above example, we did not mention any specific exception in the
except clause.
2. This is not a good programming practice as it will catch all exceptions
and handle every case in the same way.
3. We can specify which exceptions an except clause should catch.
4. A try clause can have any number of except clauses to handle different
exceptions, however, only one will be executed in case an exception
occurs.
5. We can use a tuple of values to specify multiple exceptions in an except
clause.
try:
# do something
pass
except ValueError:
# handleValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass
Raising Exceptions in Python
1. In Python programming, exceptions are raised when errors occur at
runtime.
2. We can also manually raise exceptions using the raise keyword.
3. We can optionally pass values to the exception to clarify why that
exception was raised.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Python try with else clause
1. In some situations, you might want to run a certain block of code if the
code block inside try ran without any errors.
2. For these cases, you can use the optional else keyword with the
try statement.
Note: Exceptions in the else clause are not handled by the preceding except
clauses.
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
Python try...finally
1. The try statement in Python can have an optional finally clause.
2. This clause is executed no matter what, and is generally used to
release external resources.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
Creating Custom Exceptions
1. In Python, users can define custom exceptions by creating a new class.
2. This exception class has to be derived, either directly or indirectly, from
the built-in Exception class.
3. Most of the built-in exceptions are also derived from this class.
Example: User-Defined Exception in Python
1. In this example, we will illustrate how user-defined exceptions can be
used in a program to raise and catch errors.
2. This program will ask the user to enter a number until they guess a stored
number correctly. To help them figure it out, a hint is provided whether
their guess is greater than or less than the stored number.
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# you need to guess this number
number = 10
# user guesses a number until he/she gets it right
while True:
try:
i_num = int(input("Enter a number: "))
if i_num< number:
raise ValueTooSmallError
elifi_num> number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
print("Congratulations! You guessed it correctly.")