在python的异常中,有一个万能异常:Exception,他可以捕获任意异常
s1 = 'hello' try: int(s1) except Exception as e: '丢弃或者执行其他逻辑' print(e)
输出
invalid literal for int() with base 10: 'hello'
- try-finally 语句
try-finally 语句无论是否发生异常都将执行最后的代码。
s1 = 'hello' try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) #except Exception as e: # print(e) else: print('try内代码块没有异常则执行我') finally: print('无论异常与否,都会执行该模块,通常是进行清理工作')
输出
invalid literal for int() with base 10: 'hello' 无论异常与否,都会执行该模块,通常是进行清理工作