Triggering exceptions
To cause your own exception you use the raise command. This does not have to be in
response to an illegal Python state; you can force an exception to occur at any time. Often
this is done to trap problems before an illegal state can occur. For example, you may wish
to check that two vectors are of the same length before calculating the inner product (as
above). Here it is better to have an informative error message that tells us in English that
the vectors are of different lengths, rather than reach an illegal state and get an IndexError.
The raise command takes an argument which is an exception object, and normally you
create this object right in the command itself. How to create an object is discussed in
Chapter 7
. But as an example of raise, suppose you are given a variable x and you want to
check that it is greater than zero and throw an exception if that is not true. You could do:
if x <= 0:
raise Exception('x must be > 0')
In the same way as when an illegal state triggers an exception, the raise causes Python
to look up the stack of executed commands until it finds any code that catches the
exception, but otherwise the program quits if nothing handles it. Note that in versions of
Python before 2.6 you could use strings as error objects, instead of dedicated exceptions.
However, you should not use strings as exceptions, even if you are using older versions of
Python, since it will break if someone uses the code in a newer version.
The raise command is also sometimes used in an except block because you might want
to re-throw the original exception after having done some of your own handling. In this
case the program will stop because of the error, but you have the opportunity to do
something else before the end. For example, this could be useful to do some clean-up, e.g.
to delete temporary files, close an Internet connection etc.
try:
w = x / y
except ZeroDivisionError as errorObj:
print('Program error due to zero division')
# do some clean-up (not shown)
# then re-throw exception
raise errorObj
In this case you don’t have to create an exception object because one already exists. In
fact, inside an except block Python allows you to not explicitly specify the exception
object in the raise statement, in which case it will use the one that got you into that block
in the first place:
try:
w = x / y
except:
print('Program error due to zero division')
raise
Finally
You can also add code at the bottom of a try/except block that will be executed whether or
not an exception was thrown, using finally:
try:
w = x / y
finally:
print('finished with division')
So here the final message is printed whether or not an exception occurred. This final
block of code is a convenient location for cleaning up (for example, explicitly closing files
that are open).
In older versions of Python you could not have both an except clause and a finally
clause, but that was allowed starting in Python 2.5 (the syntax for the except clause here is
only valid from Python 2.6):
try:
w = x / y
except ZeroDivisionError as e:
print('divided by zero')
finally:
print('finished with division')
Do'stlaringiz bilan baham: |