Sunday, July 3, 2011

Exception Handling

Error reporting and processing through exceptions is one of Python’s key features. In Python a programmer can raise an exception at any point in a program. When the exception is raised, program execution is interrupted as the interpreter searches back up the stack to find a context with an exception handler.

Lets start with a simple program.

>>> a=6
>>> b=0
>>> c=a/b

Python "crashes" on divide by zero.

Traceback (most recent call last):
File "", line 1, in
ZeroDivisionError: integer division or modulo by zero

Now let's try that with exception handling:

>>> a=6
>>> b=0
>>> try:
... print " a = ",a
... print " b = ",b
... c=a/b
... print " c = ",c
... except:
... print " division failed !!!"
... c=0
... print " c default to ",c
... else:
... print "division went very well"
...
This time the program will not crash, we will get an error message printed instead. Our program will continue to execute.

Our output looks like this:

a = 6
b = 0
division failed !!!
c default to 0

The statements in the try: block are attempted.The first failure jumps to the except: block If nothing in the try block fails, the program jumps to the else: block. The 1st two print statements execute, but then the try block fails, so - print 'c=',c - does not. The except block executes.The else block does not execute.

No comments:

Post a Comment