In this section we will learn how to handle the exceptions. When an exception is raised it stops the current process and calls another process. If these exceptions are not handled then they might crash the program.
We can handle the exceptions in Python by using the try statement. The operation that can raise the exception is placed inside the try block or try clause and where it will be handled is placed inside the ‘except’ clause.
Consider the following example in which the critical operations are placed inside the try statement and are caught by the ‘except’ clause:
>>> import sys
>>> myList = [‘a’, 3, 4]
>>> for x in myList:
print(“We entered”, x)
a = 1/int(x)
print(“Error!”, sys.exc_info(), “occurred”)
>>> print(“The reciprocal of”, x, “is”, a)
We entered a
Error! <class ‘ValueError’> occurred
We entered 3
The reciprocal of 3 is 0.3333333333333333
Catching Specific Exceptions in Python
In the previous example, no exception was mentioned in the ‘except’ clause. When we do not mention any exception in this clause then all the exceptions will be caught, but we can also specify the exceptions that we want to catch in the ‘except’ clause.
Consider the following example in which we have specified multiple exceptions in the ‘except’ clause by using a tuple:
except (TypeError, ZeroDivisionError):
Exceptions in Python are raised when an error is occurred at run time. An error can be raised forcefully by using the keyword raise.
Consider the following example in which we have raised an forcefully by using the ‘raise’ keyword:
>>> raise KeyboardInterrupt
Traceback (most recent call last):
File “<pyshell#60>”, line 1, in <module>
The ‘finally clause’ is optional in the ‘try clause’. Consider the following example:
f = open(“exp.txt”, encoding = ‘utf-8’)