Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Handling Exceptions

We can handle exceptions using thetry..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 theexcept clause/block. Theexcept 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 oneexcept 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 anelse clause associated with atry..catch block. Theelse 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.