31 Aug 2013

Catching an Exception in Python


Catching a exception without name: 
try:
      x = 1/0
except:
     print "it will be catched"

To get information about a exception,  use sys.exc_info() in except clause.:
excep_info = sys.exc_info()   // it returns a tuple
excep_info[0]   == type of exception
excep_info[1]  == exception message or arguments
excep_info[2]  == exception object value.


Catching a exception by name:
 try:
      x = 1/0
except ValueError:
     print "it will be catched"

or  (to get exception information)

 try:
      x = 1/0
except ValueError as exp:
     print "it will be catched"
     print type(exp)    // type of exception
     print exp.args     //exception message or argumenst


Catching exceptions by names , incorrectly :
 try:
      x = 1/0
except ZeroDivisionError, TypeError:
     print "it will be catched"

There are two issues with above code:
1) It will not catch the  ZeroDivisionError exception in a wrong way.
    Reason: except statement is interpreted  in a wrong way.
    except ZeroDivisionError as  TypeError:
    It is because in old python except ZeroDivisionError, e, anything after comma is interpreted as        alias to the exception before comma.

 TypeError is used as a reference to the ZeroDivisionError as following code shows.
      print "it will be catched", TypeError
output
     it will be catched integer division or modulo by zero

2) It will not catch the TypeError.
    Reason: since TypeError will be used as a reference.


Catching exceptions by names , correctly :
In this case either of the exception will be catched.
  try:
      x = 1/0
except ( ZeroDivisionError, TypeError ):
     print "it will be catched"


No comments:

Post a Comment