python——异常类型,,捕获异常try...


捕获异常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")
ZeroDivisionError

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
Exception

常见错误类

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=911 def test():12     global x13     print(x)14     x =115 16 test()
UnboundLocalError

官方解释法:

技术分享
 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 1011 works, but this code:12 13 >>>14 >>> x = 1015 >>> def foo():16 ...     print x17 ...     x += 118 results in an UnboundLocalError:19 20 >>>21 >>> foo()22 Traceback (most recent call last):23   ...24 UnboundLocalError: local variable ‘x‘ referenced before assignment25 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 = 1031 >>> def foobar():32 ...     global x33 ...     print x34 ...     x += 135 >>> foobar()36 1037 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 x41 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         pass12     else:13         raise MyException("自定义错误")14 except MyException as e:15     print(e)
自定义异常

python——异常类型

评论关闭