1 ''' 2 语法1: 3 try: 4 可能引发异常的代码块 5 except 异常类 as e: # 使用e作为其别名 6 异常处理代码块 7 ''' 8 9 10 def division(x, y): 11 try: 12 return x / y 13 except (ZeroDivisionError, TypeError) as e: 14 print(e) 15 16 17 print(division(10, 2)) 18 # division by zero 19 # None 20 print(division(10, 0)) 21 print(division('a', 'b')) 22 print(division(6, 3)) 23 ''' 24 输出: 25 5.0 26 division by zero 27 None 28 unsupported operand type(s) for /: 'str' and 'str' 29 None 30 2.0 31 '''
1 ''' 2 语法2: 3 import sys 4 import traceback 5 6 try: 7 # 可能引发异常的代码 8 except: 9 exc_type, exc_obj, exc_tb = sys.exc_info() 10 print("异常类型:", exc_type) 11 print("异常对象:", exc_obj) 12 print("追踪信息:") 13 traceback.print_tb(exc_tb) 14 15 1. 使用sys.exc_info()函数 16 sys.exc_info()函数返回一个包含三个值的元组,分别是当前正在处理的异常的类型、异常对象和异常的追踪信息。 17 你可以使用这些值来获取关于异常的详细信息。 18 2. 使用traceback模块 19 traceback模块提供了一些函数来打印和操作异常追踪信息。 20 你可以使用traceback.print_exc()函数直接打印完整的异常信息,或使用traceback.format_exc()函数将异常信息格式化为字符串。 21 ''' 22 import sys 23 import traceback 24 25 def division(x, y): 26 try: 27 return x / y 28 except: 29 exc_type, exc_obj, exc_tb = sys.exc_info() 30 print("异常类型:", exc_type) 31 print("异常对象:", exc_obj) 32 print("追踪信息:") 33 traceback.print_tb(exc_tb) 34 exc_str = traceback.format_exc() 35 print(f"异常格式化信息:{exc_str}") 36 37 38 print(division(10, 0)) 39 print(division('a', 'b')) 40 ''' 41 输出: 42 异常类型: <class 'ZeroDivisionError'> 43 异常对象: division by zero 44 追踪信息: 45 异常格式化信息:Traceback (most recent call last): 46 File "F:\allen_class\python\base\base\037异常\异常06-使用Python内置的错误信息2.py", line 27, in division 47 return x / y 48 ~~^~~ 49 ZeroDivisionError: division by zero 50 51 None 52 异常类型: <class 'TypeError'> 53 异常对象: unsupported operand type(s) for /: 'str' and 'str' 54 追踪信息: 55 异常格式化信息:Traceback (most recent call last): 56 File "F:\allen_class\python\base\base\037异常\异常06-使用Python内置的错误信息2.py", line 27, in division 57 return x / y 58 ~~^~~ 59 TypeError: unsupported operand type(s) for /: 'str' and 'str' 60 61 None 62 File "F:\allen_class\python\base\base\037异常\异常06-使用Python内置的错误信息2.py", line 27, in division 63 return x / y 64 ~~^~~ 65 File "F:\allen_class\python\base\base\037异常\异常06-使用Python内置的错误信息2.py", line 27, in division 66 return x / y 67 ~~^~~ 68 '''
标签:division,内置,exc,Python,traceback,错误信息,base,print,异常 From: https://www.cnblogs.com/allenxx/p/17572992.html