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
>>>