获取异常 try except
try: b=4/0 except ZeroDivisionError: print("获取 ZeroDivisionError ") ''' 获取 ZeroDivisionError '''
try: b=4/0 except ZeroDivisionError as e:# 获取更详细的信息 print('获取 ZeroDivisionError ',e) ''' 获取 ZeroDivisionError division by zero '''
import traceback try: ohmy except :# 获取调用栈的信息 print('handle unkown exception\n '+traceback.format_exc()) ''' handle unkown exception Traceback (most recent call last): File "D:\pythonProject\venv\c2.py", line 3, in <module> ohmy NameError: name 'ohmy' is not defined '''
try: ohmy except Exception as e:# 获取调用栈的信息 print('handle unkown exception: ',e) finally:#忽略错误依旧执行 print('in finally') ''' handle unkown exception: name 'ohmy' is not defined in finally '''