When there is something abnormal in your program, the exception occurs. For example, when you want to read a file, the file does not exist. Or when the program is running, you accidentally delete it. These situations can be handled using exceptions.
What happens if you have some invalid statements in your program? Python raises and tells you that there is an error, so that you can handle the situation.
Error
Consider a simple print statement. If we mistakenly spell print as print, note that uppercase, so Python throws a syntax error.
>>> Print 'Hello World'
File "<stdin>", line 1
Print 'Hello World'
^
SyntaxError: invalid syntax
>>> print 'Hello World'
Hello World
We can observe that a syntaxerror is raised and the detected error location is printed. This is the wrong processor for this error to do the work.
Try.. Except
We tried to read a segment of the user's input. 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 that it finds an unexpected end of the file (represented by ctrl-d)
Next, we will learn how to handle such errors.
Handling Exceptions
We can use try. Except statements to handle exceptions. We put the usual statements in the try-block and put our error-handling statements 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'
(source file: code/try_except.py)
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