Python学习-第八章 异常

本文深入探讨了Python中的异常处理机制,包括各种常见的异常类型及其触发条件,如ZeroDivisionError、SyntaxError等。同时,详细解释了如何使用try/except语句进行异常捕获和处理,以及如何利用else和finally子句增强代码的健壮性和可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异常

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值