try/except 捕捉由Python或你引起的异常并恢复 try/finally 无论异常是否发生,执行清理行为 raise 手动在代码中触发异常 assert 有条件地在程序代码中触发异常 with/as 在python2.6和后续版本中实现环境管理器
捕获异常:
def catcher(): try: fetcher(x, 4) except IndexError: print 'got exception' >>'got exception'
引发异常:
try: raise IndexError except IndexError: print 'got exception' >>'got exception'
用户定义的异常:
class Bad(Exception): pass def doomed(): raise Bad() try: domed() except Bad: print 'got Bad' >>'got Bad'
终止行为: 无论是否有错误,都会触发finally
try: fetcher(x, 3) finally: print 'after fetch' 'm' 'after fetch'
完全体
try: ... except NameError: ... except IndexErrot: ... except: ... else: ... finally: ...