Learning Python

Chapter 33: Exception Basics

2021-06-19  本文已影响0人  枇杷膏_a56b

Exception statements

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:
    fetcher(x, 4)
except IndexError:
    print('got exception') 
print('continuing') 

>>>
got exception
continuing

Raising Exceptions

try:
    raise IndexError
except IndexError:
    print('got exception') 

>>>
got exception
raise IndexError 

>>>
IndexError                                Traceback (most recent call last)
<ipython-input-7-685a1d98d309> in <module>
----> 1 raise IndexError

IndexError: 
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
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

# 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
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

上一篇下一篇

猜你喜欢

热点阅读