Saturday, September 19, 2009

Python - try except - error handling in python

import sys

# simple error catch
try:
    # an obvious error
    a = 1/0
except ZeroDivisionError as err:
    print "Specific Exception: ", err
    print ""

# catch one of several specific
try:
    a = 1/0
except (ZeroDivisionError, ValueError, IOError) as err:
    print "One of several Exceptions: ", err
    print ""
   
# catch all exceptions
try:
    a = 1/0
except:
    print "Generic Catchall"
    for i in sys.exc_info():
        print i
    print ""

# you can also do a combo
try:
    a = 1/0
except ZeroDivisionError as err:
    print "Combo: ", err
    print ""
except (ZeroDivisionError, ValueError, IOError) as err:
    print "Combo: One of several Exceptions: ", err
    print ""
except:
    print "Combo: Generic Catchall"
    for i in sys.exc_info():
        print i

       
## output:
##Specific Exception:  integer division or modulo by zero
##
##One of several Exceptions:  integer division or modulo by zero
##
##Generic Catchall
##
##integer division or modulo by zero
##
##
##Combo:  integer division or modulo by zero
   


No comments:

Post a Comment