Exception Handling in Python
by Phillip Watts
July 23, 2009
|
Today Phillip Watts introduces us to the robust and elegant
Python error handling methods.
|
Introduction
All modern high level computer languages, and most
ancient ones, have built-in constructs and methods for the
handling of errors or exceptions. I will loosely define an
error as anything which could happen, though you hope that
it does not, which will cause the program to fail. "Fail"
could mean the program crashes, or it could mean that the
program is going to produce meaningless results.
I must say this to the beginning programmer: once you
begin using networks, servers, databases, or even text files
you have built yourself, you are wide open to errors. And
the possibilities become endless. If you like, you can wait
until errors occur then patch in the solutions. It is much
wiser to anticipate the conditions which bad data could
cause, and make this a part of your program plan.
Python has robust and elegant error handling methods, and
this article will provide an introduction to those methods.
The reader of this article should have at least a minimum
familiarity with Python, or something comparable such as
Java or Ruby.
Let us start with a simple example, a
try/except/else:
First a simple prgoram:
#!/usr/bin/env python
a = 2
b = 0
c = a / b
The division operation, in this example, is doomed to failure.
Python "crashes" on divide by zero.
Traceback (most recent call last):
File "./sample.py", line 4, in <module>
c = a / b
ZeroDivisionError: integer division or modulo by zero
Now let's try that with exception handling:
#!/usr/bin/env python
import sys
a = 2
b = 0
try:
print 'a=',a
print 'b=',b
c = a / b
print 'c=',c
except:
print 'division failed miserably'
c = 0
print 'c defaults 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.
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.
And our output looks like this:
a= 2
b= 0
division failed miserably
c defaults to 0
In this simple example, I set a default value for c in
the except block. I am presuming that an undefined value for
c will cause problems later. I could have set a default
value for c before the stament which failed. This would have
worked just as well. The statement which failed would not
have altered the value of c.
Exception Handling in Python
Exception Handling in Python - Cont.
|