Exception handling is a core part of the Python language.
There are a number of reasons why using exceptions is a good idea:
(a) exceptions offer protection against unexpected conditions(b) exceptions can deliver on-screen messages for warning and error reporting
(c) exceptions are an alternative to the print statement for debugging
Exceptions are especially useful in code associated with error-prone processes, for example data input, file operations and wireless communications.
So, what does a Python exception handler look like?
Here's a simple example:
try:
x = int(raw_input("Please enter a number: ")
break
except ValueError:
print "Not a valid number. Please try again..."
The try
part of the exception asks the user for a number. While the exception
part tests for non-numeric values and reports problems back to the user. So this is a combination of the '(a)' an '(b)' scenarios above.
Here's a more elaborate example:
try:
f = open(fname, 'r')
except IOError:
print 'Can't open file: ', fname
else:
print fname, ' contains ', len(f.readlines()), ' lines '
f.close()
This time we only try to do something with the file fname
if the open()
operation is successful. Otherwise we notify the user of the problem.
Take a look at some non-trivial Python source code to see if you spot the exception handlers and work out why they exist.