Pages

Thursday, November 11, 2010

Exceptions


Exceptions occur when certain exceptional situations occur in your program. For example, what if you
are going to read a file and the file does not exist? Or what if you accidentally deleted it when the program
was running? Such situations are handled using exceptions.
What if your program had some invalid statements? This is handled by Python which raises its hands
and tells you there is an error.

Errors

Consider a simple print statement. What if we misspelt print as Print? Note the capitalization. In
this case, Python raises a syntax error.
>>> Print 'Hello World'
File "<stdin>", line 1
Print 'Hello World'
^
SyntaxError: invalid syntax
>>> print 'Hello World'
Hello World


Observe that a SyntaxError is raised and also the location where the error was detected is printed.
This is what an error handler for this error does.

Try..Except

We will try to read input from the user. Press Ctrl-d and see what happens.
>>> s = raw_input('Enter something --> ')
Enter something --> Traceback (most recent call last):
File "<stdin>", line 1, in ?
EOFError


Python raises an error called EOFError which basically means it found an end of file when it did not
expect to (which is represented by Ctrl-d)
Next, we will see how to handle such errors.
Handling Exceptions
We can handle exceptions using the try..except statement. We basically put our usual statements
within the try-block and put all our error handlers in the except-block.

Example 13.1. Handling Exceptions
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'


Output
$ python try_except.py
Enter something -->
Why did you do an EOF on me?
$ python try_except.py
Enter something --> Python is exceptional!
Done


How It Works
We put all the statements that might raise an error in the try block and then handle all the errors and
exceptions in the except clause/block. The except clause can handle a single specified error or exception,
or a parenthesized list of errors/exceptions. If no names of errors or exceptions are supplied, it
will handle all errors and exceptions. There has to be at least one except clause associated with every
try clause.
If any error or exception is not handled, then the default Python handler is called which just stops the execution
of the program and prints a message. We have already seen this in action.
You can also have an else clause associated with a try..catch block. The else clause is executed
if no exception occurs.
We can also get the exception object so that we can retrieve additional information about the exception
which has occurred. This is demonstrated in the next example.

No comments:

Post a Comment