Python Exception : Python Tutorial 23

Python Exception : What is an Exception :

Exceptions are errors that raised during execution time. That means your statement is correct but during execution time , it was trying to run a statement that cannot be done . Let’s take an example on a python exception :

for i in range(5,-1,-1):
    print 5/i

Output :

1
1
1
2
5
Traceback (most recent call last):
  File "temp.py", line 2, in 
    print 5/i
ZeroDivisionError: integer division or modulo by zero

i.e. the program was able to run for i = 5 , 4, 3, 2 and 1 . But for i= 0, it throws an exception “ZeroDivisionError” as dividing a number by “0” is not possible.

This exception is a built-in exception , i.e. it is already defined . If a built-in exception occurs, python prints the Name of the Exception and one description. Now, let’s check what happens if an exception is raised :

for i in range(5,-1,-1):
    print 5/i

print ("for loop completed")

After the exception will occure, it will not execute the final “print” line , i.e. the program will stop executing.

Handling Exceptions in python :

We can write programs to handle exceptions manually. Change the above example as below :


try:
    for i in range(5,-1,-1):
        print 5/i
except ZeroDivisionError:
    print "zero division error !!"
print ("for loop completed")

Run this program and the output will be :

1
1
1
2
5
zero division error !!
for loop completed

i.e. , if an exception occurs in the try block, it stop its execution of try-block and moves to the “except” block, runs it and continue execution below try-except .

More than one exception type handling in python :

In the above example, we are handling only one error : ZeroDivisionError. We can also write “except” condition to handle more than one exception as like below :

except (RuntimeError, TypeError, ZeroDivisionError) :
    ……

Here , RuntimeError, TypeError, ZeroDivisionError all these three errors will be handled .

Multiple errors also can be handled as like below :

try :
    // try code
except ValueError as e :
    print “Value Error “,e.strerror
except IOError :
    print “IOError ..except :
    print “Unknown exception …”

In this example, we have different except statement for all the three different exceptions. So, we can confirm, what is the actual cause of the exception. If an exception not listed in the “except” blocks are raised, it will run the final “except” block.

try…except….else :

We can also add one extra optional “else” block with try-except statements. It is useful to execute code that must be executed always if try clause does not raise an exception.

try :
    f = open("myfile","w")
    f.write("Hello World !!")
except IOError :
    print "Not able to read/write on the file "
else :
    print "File execution successfully completed"
    f.close()

try..finally :

If you want to execute a piece of code wheather any exception is raised or not in the try block, then place it inside finally block. You cannot use else with finally.

try:
   f = open("myfile", "w")
   try:
      f.write("Hello World !!")
   finally:
      print ("closing the file")
      f.close()
except IOError:
   print "Cannot read/write file"

It will first run the try block. If any exception occurs, it will move to the finally block, and then except block . If no exception is raised, then also it will move to the finally block.

Raising an exception :

For raising an exception in python, we can use “raise” statement . An argument can also be passed with the exception :

try:
    for i in range(5,-1,-1):
        if i == 0 :
            raise ZeroDivisionError("trying to divide by zero..")
        else :
            print 5/i
except ZeroDivisionError as e:
    print e

It will print :

1
1
1
2
5
trying to divide by zero..

Custom Exception in python :

You can also create your own exception in python. We can create a new class for these types of exceptions. But , all custom exceptions should derive “Exception” class directly or indirectly. Following example will clarify your doubts :

class Error(Exception):
pass

class MyCustomError(Error):
print "Custom error...."
pass

try:
raise MyCustomError
except MyCustomError:
pass

Here we have first create one base class “Error” and then the custom exception class “MyCustomError” . “MyCustomError” is derived from “Error” class.

Similar tutorials :