Exception Handling


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.

 

Catching Exceptions in Python

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:

CODE

>>> import sys

>>> myList = [‘a’, 3, 4]

>>> for x in myList:

          try:

                   print(“We entered”, x)

                   a = 1/int(x)

                   break

          except:

                   print(“Error!”, sys.exc_info()[0], “occurred”)

                   print(“Next Item”)

                   print()

>>> print(“The reciprocal of”, x, “is”, a)

OUTPUT

We entered a

Error! <class ‘ValueError’> occurred

Next Item

We entered 3

The reciprocal of 3 is 0.3333333333333333

reciprocal

 

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:

CODE

 >>> try:

          pass

except ValueError:

          pass

except (TypeError, ZeroDivisionError):

          pass

except:

          pass

pass

 

Raising Exceptions

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:

CODE

>>> raise KeyboardInterrupt

OUTPUT

Traceback (most recent call last):

  File “<pyshell#60>”, line 1, in <module>

    raise KeyboardInterrupt

KeyboardInterrupt

keyboardinterrupt

 

try… finally

The ‘finally clause’ is optional in the ‘try clause’. Consider the following example:

CODE

>>> try:

          f = open(“exp.txt”, encoding = ‘utf-8’)

finally:

          f.close()