A Byte of Python


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 ?

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

# Filename: try_except.py

import sys

	s = raw_input('Enter something --> ')
except EOFError:
	print '\nWhy did you do an EOF on me?'
	sys.exit() # exit the program
	print '\nSome error/exception occurred.'
	# here, we are not exiting the program

print 'Done'


$ python try_except.py
Enter something -->
Why did you do an EOF on me?

$ python try_except.py
Enter something --> Python is exceptional!

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.