python try exception类_python——异常类型

捕获异常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 exceptException 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 deftest():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 deftest():12 globalx13 print(x)14 x =1

15

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 inthe body of a function.2

3 This code:4

5 >>>

6 >>> x = 10

7 >>> defbar():8 ... printx9 >>>bar()10 10

11 works, but this code:12

13 >>>

14 >>> x = 10

15 >>> deffoo():16 ... printx17 ... x += 1

18 results inan 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 andan 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 >>> deffoobar():32 ... globalx33 ... printx34 ... 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 inthe outer scope:38

39 >>>

40 >>> printx41 11

官方

ValueError 传入不期望值

自定义异常

自定义异常通过继承异常基类的方法的派生类。(好绕嘴)如下:

1 classMyException(Exception):2 def __init__(self,name):3 self.msg =name4

5 def __str__(self):6 return self.msg #可以不重写,继承基类

7

8 #调用

9 try:10 ifflag:11 pass

12 else:13 raise MyException("自定义错误")14 exceptMyException as e:15 print(e)

自定义异常

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值