relatively graceful manner. Note that it is commonplace to say ‘throw an exception’ to
mean that an exception was generated by some illegal program state. Here is a very simple
Rather than simply letting such things always break the program, Python allows you to
it, and potentially let the program carry on afterwards. The simplest version is:
block and instead executes the code in the except block. In the above case, every kind of
exception error is trapped, so there is no way of knowing what kind of exception it was.
However, you can specify what kind of exception is trapped. Python has many inbuilt
try:
z = x + y
w = x / y
t = x * y
except ZeroDivisionError:
print('divided by zero')
print('program did not stop')
In this specific example, an exception occurs in the calculation of w, so it is not set and,
further, the calculation of t never happens and an error message is printed instead. Because
the illegal division by zero was dealt with the program can then continue. You can even
get hold of an exception object, which can be printed out to show the internal Python error
message:
x = 1
y = 0
try:
w = x / y
except ZeroDivisionError as errorObj:
print(errorObj) # prints 'integer division or modulo by zero'
print('program did not stop')
Before Python 2.6 the syntax for catching the exception object was different, so if you
are using an older version of Python then you have to use a comma instead of ‘as’ (the
comma syntax also works in Python 2.6 and 2.7 but not in Python 3):
try:
w = x / y
except ZeroDivisionError, errorObj:
print(errorObj) # prints 'integer division or modulo by zero'
This reports the Python message about what happened, which you would get if the
program failed, but naturally because we used the try: clause to catch the problem the
program did not stop. There is a simple ‘base’ exception in Python called Exception, and
that lets you trap all types of exception and get hold of the exception object:
try:
# code block that might throw an exception
except Exception as errorObj:
# exception handling code
Also, you can catch different types of exception by repeating the except statement. This
allows different problems to be handled in different ways. For example, if you try to
divide something by a text string (or a string by something) in Python you get a
TypeError. So your division code could check for this and for zero division, printing an
appropriate message for each situation:
try:
w = x / y
except ZeroDivisionError as errorObj:
print('divided by zero', errorObj)
except TypeError as errorObj:
print('divided by something silly', errorObj)
Do'stlaringiz bilan baham: