

try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?' sys.exit() # exit the program
$ python try_except.py
Enter something -->
Why did you do an EOF on me?
$ python try_except.py
Enter something --> Python is exceptional! Done
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.