1、
一些内置的异常类
类名 | 描述 |
---|---|
Exception | 几乎所有的异常类都是从它派生的 |
AttributeError | 引用属性或给它赋值失败时引发 |
OSError | 操作系统不能执行指定的任务时引发,有多个子类 |
IndexError | 使用序列中不存在的索引时引发,为LookupError的子类 |
KeyError | 使用映射中不存在的键时引发,为LookupError的子类 |
NameError | 找不到名称(变量)时引发 |
SyntaxError | 代码不正确时引发 |
TypeError | 将内置操作或函数用于类型不正确的对象时引发 |
ValueError | 将内置操作或函数用于这样的对象时引发:其类型正确但包含的值不合适 |
ZeroDivisionError | 在除法或球模运算的第二参数为零时引发 |
2、异常捕捉
如果想要一个except子句捕捉多种异常,可在一个元组中指定这些异常
>>> try:
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
print(x / y)
>>> except (ZeroDivisionError, TypeError, ValueError):
print("Your number were illegal.")
3、更高效的异常捕捉
有时候没有预测到会出现的异常,可以使用except语句,但不指定任何异常类,就可以捕捉所有异常。
try:
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
print(x / y)
except:
print("Your number were illegal.")
但是这样捕捉所有异常很危险,这会隐藏没有考虑到的错误。
4、如果只想发出警告,指出情况偏离正轨,可以使用模块warnings中的函数warn
>>> from warnings import warn
>>> warn("I've got a bad feeling about this.") #警告只显示一次
<string>:1: UserWarning: I've got a bad feeling about this.
>>> warn("I've got a bad feeling about this.") #再次运行代码什么都不发生
>
pass