异常
raise
raise
语句以Exception子类为参数, 抛出异常:
>>> raise Exception("Overload")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise Exception("Overload")
Exception: Overload
一些内置的异常类:
类名 | 描述 |
---|---|
Exception | 几乎所有的异常类都是从它派生而来的 |
AttributeError | 引用属性或给它赋值失败时引发 |
OSError | 操作系统不能执行指定的任务(如打开文件)时引发,有多个子类 |
IndexError | 使用序列中不存在的索引时引发,为LookupError的子类 |
KeyError | 使用映射中不存在的键时引发,为LookupError的子类 |
NameError | 找不到名称(变量)时引发 SyntaxError 代码不正确时引发 |
TypeError | 将内置操作或函数用于类型不正确的对象时引发 |
ValueError | 将内置操作或函数用于这样的对象时引发:其类型正确但包含的值不合适 |
ZeroDivisionError | 在除法或求模运算的第二个参数为零时引发 |
自定义异常类:
# 从Exception中直接或间接派生
>>> class MyException(TypeError): pass
>>> raise MyException
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
raise MyException
MyException
捕获异常(P134)
try:
1/0
except ZeroDivisionError:
print("ZeroDivisionError")
使用异常机制代替if检查会更方便
捕获异常后, 如果要使它向上传播可调用raise且不提供任何参数
进入except的异常会作为异常上下文存储起来, 并且会出现在最终的消息中, 如果想要自定义异常上下文, 可以使用raise ... from ...
语句, 使用raise ... from ...
可以禁用异常上下文
# 异常上下文
try: 1/0
except ZeroDivisionError: raise ValueError
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
try: 1/0
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#12>", line 2, in <module>
except ZeroDivisionError: raise ValueError
ValueError
# 自定义异常上下文
>>> raise ZeroDivisionError from TypeError
TypeError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
raise ZeroDivisionError from TypeError
ZeroDivisionError
可以使用一个except语句捕获多个异常, 用as语句获得捕获的异常对象:
except (NameError, ZeroDivisionError) as e: print(e)
使用不带任何参数的except语句捕获全部异常:
try :
x = input()
except:
pass
# 将捕获所有异常, 包括用户使用Ctrl+C终止程序的企图
try/except语句中的else子句会在没有出现异常是执行:
try: print("Hello")
except: print("Wrong")
else: print("Right")
Hello
Right
finally子句与try配套, 用于在发生异常后进行处理工作, 无论发生什么异常都会执行finally子句, 可以用于确保文件或网络套接字得以关闭:
try: 1/0
except Exception as e: print(e)
finally: print("finally")
division by zero
finally
警告(P142)
>>> from warnings import warn
>>> warn("123")
Warning (from warnings module):
File "C:\Users\Lee\Desktop\test.py", line 1
try:
UserWarning: 123
>>> warn("123")
>>>
# 警告消息只显示一次