@异常处理
1.基本异常处理
1 #基本的异常处理 2 3 inp = input('请输入您的内容:') 4 5 try: 6 num = int(inp) 7 print(num) 8 9 except Exception as e: 10 print("数据类型转换失败!")
2.异常分类
1 #异常分类 2 3 #Exception是所有错误分类的基类 4 5 6 inp = input('请输入您的内容:') 7 8 try: 9 num = int(inp) 10 print(num) 11 12 except ValueError as e: 13 print('值异常') 14 except IndexError as e: 15 print('索引异常') 16 except Exception as e: #Exception之上错误类优先匹配,可计入日志,如果没有,执行Exception,万能匹配 17 print("数据类型转换失败!")
3.完整异常处理代码块
1 try: 2 # 主代码块 3 pass 4 except ValueError as e: 5 # 异常时,执行该块 6 pass 7 except IndexError as e: 8 # 异常时,执行该块 9 pass 10 except Exception as e: 11 # 异常时,执行该块 12 pass 13 14 else: 15 # 主代码块执行完,执行该块 16 pass 17 18 finally: 19 # 无论异常与否,最终执行该块 20 pass
4.主动触发异常
1 #主动触发异常 2 inp = input('请输入您的内容:') 3 4 5 try: 6 print(inp) 7 raise Exception('错误了') #主动触发异常,创建错误对象并赋值给e 8 9 except Exception as e: 10 print(e)
5.自定义异常处理和str字符串方法
1 #自定义异常处理和str字符串方法 2 3 class meiyuException(Exception): 4 def __init__(self, msg): 5 self.message = msg 6 7 def __str__(self): 8 return self.message 9 10 try: 11 raise meiyuException('我的异常') 12 13 except meiyuException as e: 14 print(e) #执行__str__方法
6.断言
1 #断言 ##可用于测试等场景 2 3 # assert 条件 4 5 # assert 1==2
7.更多异常类型
1 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x 2 IOError 输入/输出异常;基本上是无法打开文件 3 ImportError 无法引入模块或包;基本上是路径问题或名称错误 4 IndentationError 语法错误(的子类) ;代码没有正确对齐 5 IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5] 6 KeyError 试图访问字典里不存在的键 7 KeyboardInterrupt Ctrl+C被按下 8 NameError 使用一个还未被赋予对象的变量 9 SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了) 10 TypeError 传入对象类型与要求的不符合 11 UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量, 12 导致你以为正在访问它 13 ValueError 传入一个调用者不期望的值,即使值的类型是正确的
1 ArithmeticError 2 AssertionError 3 AttributeError 4 BaseException 5 BufferError 6 BytesWarning 7 DeprecationWarning 8 EnvironmentError 9 EOFError 10 Exception 11 FloatingPointError 12 FutureWarning 13 GeneratorExit 14 ImportError 15 ImportWarning 16 IndentationError 17 IndexError 18 IOError 19 KeyboardInterrupt 20 KeyError 21 LookupError 22 MemoryError 23 NameError 24 NotImplementedError 25 OSError 26 OverflowError 27 PendingDeprecationWarning 28 ReferenceError 29 RuntimeError 30 RuntimeWarning 31 StandardError 32 StopIteration 33 SyntaxError 34 SyntaxWarning 35 SystemError 36 SystemExit 37 TabError 38 TypeError 39 UnboundLocalError 40 UnicodeDecodeError 41 UnicodeEncodeError 42 UnicodeError 43 UnicodeTranslateError 44 UnicodeWarning 45 UserWarning 46 ValueError 47 Warning 48 ZeroDivisionError
浙公网安备 33010602011771号