【Python】异常处理,try...

1 raise手动引发异常

可以使用raise手动引发异常,并将一个类(Exception的子类)或实例作为参数

>>> raise Exception("raise test")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: raise test
>>>

常用的内置异常类

类名描述
Exception几乎所有的异常类都是由它派生而来的
AttributeError引用属性或者给他赋值失败时引发
OSError操作系统不能执行指定的任务(如打开文件)时引发,有多个子类
IndexError使用序列中不存在的索引时引发,为LookupError的子类
KeyError使用映射中不存在的键时引发,为LookupError的子类
NameError找不到名称(变量)时引发
SyntaxError代码不正确时引发
TypeError将内置参数或者函数用于类型不正确的对象时引发
ValueError将内置参数或者函数用于这样的对象时引发:其类型正确但是值不合适
ZeroDivisionError在除法或者求模运算时第二个参数为0

2 try/except异常捕获

try后面可以接多个语句,但是当语句异常时则后面的语句将不再执行。一个try语句可以接多个except。

>>> print(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> try:
...     1/0
...     print(a)
... except ZeroDivisionError:
...     print("division by zero")
... except NameError:
...     print("aa")
...
division by zero
>>> try:
...     1/1
...     print(a)
... except ZeroDivisionError:
...     print("division by zero")
... except NameError as e:
...     print(e)
...
1.0
name 'a' is not defined
>>> try:
...     1/0
... except (NameError,ZeroDivisionError):
...     print("something is wrong!")
...
something is wrong!
>>>

当发生异常时如果异常没有被处理则会继续向上传播直到被处理或者程序终止。
如果无法处理异常,在except中使用不带参数的raise通常是不错的选择,但是有时你可能想引发其他异常,这样导致进入except字句的异常将被作为异常上下文存储起来,并出现在最终的错误消息中,当有时候觉得异常上下文太多,甚至有些是干扰信息时,可以使用raise…from None来禁用上下文。

>>> try:
...     1/0
... except ZeroDivisionError:
...     raise ValueError from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError
>>> try:
...     1/0
... except ZeroDivisionError:
...     raise
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
>>> try:
...     1/0
... except ZeroDivisionError:
...     raise ValueError
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError
>>>

3 else & finally

else:try里面所有的语句都执行成功时执行。
finally:不管try里面的语句是否异常总是执行finally的语句,一般用于执行清理工作。

>>> while True:
...     try:
...             x = int(input("enter the first num: "))
...             y = int(input("enter the second num: "))
...             value = x/y
...             print("x/y is:", value)
...     except Exception as e:
...             print("invalid input:", e)
...             print("pls try again!")
...     else:
...             break
...     finally:
...             print("cleaning up")
...
enter the first num: 1
enter the second num: 0
invalid input: division by zero
pls try again!
cleaning up
enter the first num: 2
enter the second num: a
invalid input: invalid literal for int() with base 10: 'a'
pls try again!
cleaning up
enter the first num: 1
enter the second num: 5
x/y is: 0.2
cleaning up
>>>

4 warn稍微警告一下

warn通常只打印错误消息,不会影响后面动作的执行

>>> from warnings import warn
>>> from warnings import filterwarnings
>>> warn("sth wrong?")
__main__:1: UserWarning: sth wrong?
>>> try:
...     warn("sth wrong?")
...     print("you can see me. ^_^")
... except:
...     print("you can't see me. T.T")
...
__main__:2: UserWarning: sth wrong?
you can see me. ^_^
>>> filterwarnings("ignore")
>>> warn("sth wrong?")
>>> filterwarnings("error")
>>> warn("sth is very wrong")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UserWarning: sth is very wrong
>>>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值