Chapter 33: Exception Basics
2021-06-19 本文已影响0人
枇杷膏_a56b
Exception statements
-
try/except
Catch and recover from exceptions raised by Python. -
try/finally
Perform cleanup actions, whether exceptions occur or not. -
raise
Trigger an exception manually in your code. -
assert
Conditionally trigger an exception in your code. -
with/as
implement context managers in Python 2.6, 3.0, and later.
Exceptions: The short story
Default Exception Handler
def fetcher(obj, index):
return obj[index]
x = 'spam'
fetcher(x, 3 )
>out:
'm'
# Trigger error
fetcher(x, 4)
>out:
IndexError Traceback (most recent call last)
<ipython-input-2-21dabc2ad673> in <module>
----> 1 fetcher(x, 4)
<ipython-input-1-cda73fc8bc2e> in fetcher(obj, index)
1 def fetcher(obj, index):
----> 2 return obj[index]
3
4
5 x = 'spam'
IndexError: string index out of range
Catching Exceptions
try:
fetcher(x, 4)
except IndexError:
print('got exception')
>out:
got exception
- try statements can recover from the error
try:
fetcher(x, 4)
except IndexError:
print('got exception')
print('continuing')
>>>
got exception
continuing
Raising Exceptions
- Trigger the exceptions directly
try:
raise IndexError
except IndexError:
print('got exception')
>>>
got exception
- raize can trigger default error handler if it is not been caught
raise IndexError
>>>
IndexError Traceback (most recent call last)
<ipython-input-7-685a1d98d309> in <module>
----> 1 raise IndexError
IndexError:
- assert statement can trigger exceptions
assert False, 'Assert exception has been triggered.'
>>>
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-8-4fb192a323b1> in <module>
----> 1 assert False, 'Assert excetpion has been triggered.'
AssertionError: Assert exception has been triggered.
User-Defined Exceptions
class AlreadyGotOne(Exception):
pass
def grail():
raise AlreadyGotOne
try:
grail()
except AlreadyGotOne:
print('got exception')
>>>
got exception
- By doing this, any one can define his/her own exceptions.
class Career(Exception):
def __str__(self):
return 'So I became a waiter...'
raise Career()
>>>
---------------------------------------------------------------------------
Career Traceback (most recent call last)
<ipython-input-13-f965ba3ecc05> in <module>
5
6
----> 7 raise Career()
Career: So I became a waiter...
Termination Actions
- Including finally to terminate the program.
# program does not resume after processing finally block if exception is triggered.
try:
fetcher(x, 4)
finally:
print('after fetch.')
print('after try.')
>>>
after fetch.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-15-00f50b38a986> in <module>
1 try:
----> 2 fetcher(x, 4)
3 finally:
4 print('after fetch.')
5 print('after try.')
<ipython-input-1-cda73fc8bc2e> in fetcher(obj, index)
1 def fetcher(obj, index):
----> 2 return obj[index]
3
4
5 x = 'spam'
IndexError: string index out of range
# The program continues after finally block is processed if no exception is triggered.
try:
fetcher(x, 3)
finally:
print('after fetch.')
print('after try.')
>>>
after fetch.
after try
- You can use finally block to ensure the opened file is closed or disconnect servers.
- A general model for error handling in Python
def do_stuff():
do_1st_thing()
do_2nd_thing()
...
do_last_thing()
if __name__ == '__main__':
try:
do_stuff()
except:
bad_ending()
else:
good_ending()
Summary
- Exception processing is useful for error handling, termination actions, and event notification.
- Any uncaught exception eventually filters up to the default exception handler.
- raise and assert statements can be used to trigger an exception, exactly as if it had been raised by Python itself.
- The try/finally and with (only works with the objects that support it) can ensure some statements are executed whether the exceptions occur or not.