捕获异常try...except...finally...else
python为高级语言,就是通过try...except...finally...else机制来处理错误。
让我们来看一下这段错误代码:
1 try: 2 print("try...") 3 s = 10/0 #异常,之后代码不执行 4 print("not run this code") 5 except ZeroDivisonError as e: #有错误执行一下语句 6 print("except",e) 7 finally: 8 print("finally...") # 有没有错误都要执行finally;此处可以不加 9 print("END")
try下加入要执行代码,如果代码某处发生错误,错误之后代码段不执行直接跳到except捕获的错误类型抛出错误提示,最后走finally执行完毕,这里finally可有可无。else没有错误发生时执行。
如果你不知道执行代码段可能发生什么种类的错误,可以捕获全部错误,比如:
1 try: 2 f = open("unexsit.file","r") 3 f.read() 4 except Exception as e: 5 print("出错了,但是什么类型呢,打印一下吧",e) 6 7 #[Errno 2] No such file or directory: unexsit.file
常见错误类
AttributeError 不存在属性
IoError 输入或输出异常
ImportError 无法引入模块或包。(一般是路径问题或模块名称有误)
IndentationError 语法错误(SyntaxError子类),一般是代码缩进错误
KeyError 字典中不存在关键字
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个未被赋予对象的变量
SyntaxError 语法错误
TypeError 传入对象类型与要求不符
UnboundLocalError 变量作用域的问题(详见:https://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value)
1 x=9 2 3 def test(): 4 print(x)# 5 x =1#python从上到下解释,会吧x当做局部变量,然而上边print要打印未声明的局部变量,报错 6 7 test() 8 #UnboundLocalError: local variable 'x' referenced before assignment 9 //修改 10 x=9 11 def test(): 12 global x 13 print(x) 14 x =1 15 16 test()
官方解释法:
1 It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function. 2 3 This code: 4 5 >>> 6 >>> x = 10 7 >>> def bar(): 8 ... print x 9 >>> bar() 10 10 11 works, but this code: 12 13 >>> 14 >>> x = 10 15 >>> def foo(): 16 ... print x 17 ... x += 1 18 results in an UnboundLocalError: 19 20 >>> 21 >>> foo() 22 Traceback (most recent call last): 23 ... 24 UnboundLocalError: local variable 'x' referenced before assignment 25 This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print x attempts to print the uninitialized local variable and an error results. 26 27 In the example above you can access the outer scope variable by declaring it global: 28 29 >>> 30 >>> x = 10 31 >>> def foobar(): 32 ... global x 33 ... print x 34 ... x += 1 35 >>> foobar() 36 10 37 This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope: 38 39 >>> 40 >>> print x 41 11
ValueError 传入不期望值
自定义异常
自定义异常通过继承异常基类的方法的派生类。(好绕嘴)如下:
1 class MyException(Exception): 2 def __init__(self,name): 3 self.msg = name 4 5 def __str__(self): 6 return self.msg # 可以不重写,继承基类 7 8 #调用 9 try: 10 if flag: 11 pass 12 else: 13 raise MyException("自定义错误") 14 except MyException as e: 15 print(e)