Python学习-第八章 异常

异常

Python使用异常对象来表示异常状态,并在遇到错误时引发异常。异常对象未被处理(或捕获)时,程序将终止并显示一条错误消息。

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

异常捕获示例:

>>> try:
...    x=int(input('Enter the first number:'))
...    y=int(input('Enter the second number:'))
...    print(x/y)
... except ZeroDivisionError:
...    print("The second number can't be zero!")
...
Enter the first number:1
Enter the second number:0
The second number can't be zero!

捕获异常后,如果要重新引发它(即继续向上传播),可调用raise且不提供任何参数(也可以显式地提供捕获的异常)
发生除零行为时,如果启用了“抑制”功能,方法calc将(隐式地)返回None。换而言之,如果启用了“抑制”功能,就不应依赖返回值。

>>> class MuffledCalculator:
...    muffled=False
...    def calc(self,expr):
...       try:
...          return eval(expr)
...       except ZeroDivisionError:
...          if self.muffled:
...             print('Division by zero is illegal')
...          else:
...              raise
...
>>> calculator=MuffledCalculator()
>>> calculator.calc('10/2')
5.0
>>> calculator.calc('10/0')     #关闭了抑制功能
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in calc
  File "<string>", line 1, in <module>
ZeroDivisionError: division by zero
>>> calculator.muffled=True
>>> calculator.calc('10/0')
Division by zero is illegal

可以给try/except语句添加一个else子句,当代码段没有引发异常时,才会跳出循环。

>>> while True:
...    try:
...       x=int(input('Enter the first number:'))
...       y=int(input('Enter the second number:'))
...       value=x/y
...       print('x/y is',value)
...    except:
...       print('Invalid input.Please try again.')
...    else:
...       break
...
Enter the first number:1
Enter the second number:0
Invalid input.Please try again.
Enter the first number:'foo'
Invalid input.Please try again.
Enter the first number:baz
Invalid input.Please try again.
Enter the first number:10
Enter the second number:2
x/y is 5.0

当try/except中用到finally是为了发生异常时执行清理工作。不管try子句中发生什么异常,都将执行finally子句。

>>> x=None
>>> try:
...     x=1/0
... finally:
...     print('Cleaning up...')
...     del x
...
Cleaning up...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

如果只想发出警告,可使用模块warning中的函数warn
如果其他代码在使用你的模块,可使用模块warning时 中的函数filterwarnings来抑制你发出的警告

>>> from warnings import filterwarnings
>>> filterwarnings("error")
>>> warn("This function is really old...",DeprecationWarning)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
DeprecationWarning: This function is really old...
>>> filterwarnings("ignore",category=DeprecationWarning)
>>> warn("Another deprecation warning.",DeprecationWarning)
>>> warn("Something else.")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UserWarning: Something else.

猜你喜欢

转载自blog.csdn.net/weixin_43340018/article/details/83307601