python3xiaobaike_2020/chapter8/8-2 python3小白课:多异常捕获.md
2025-04-20 23:22:14 +08:00

65 lines
2.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# python3小白课多异常捕获
`Exception`类之下还有许多其他的从它继承的异常类。我们可以针对不同的具体异常做针对性处理写多个except块也可以将多个子类异常合并到一起处理我们来看一下语法
```python
## 多个异常类单独处理
try:
# 业务语句
...
except Exception1: # as e这样的部分不是必须的
# 处理Exception1异常的语句
...
except Exception2:
# 处理Exception2异常的语句
...
except Exception3:
# 处理Exception3异常的语句
...
except: # Exception也不是必须的这样也可以捕获所有类型的异常通常写在最后一个
# 处理其他未知异常的语句
...
## 也可以多个异常合成一个处理
try:
# 业务语句
...
except (Exception1, Exception2, Exception3):
# 处理框定这些异常的语句
...
except:
# 处理其他未知异常的语句
...
```
咱们来看一个小例子再巩固一下吧:
```python
# coding:utf-8
import sys
while True:
try:
a = int(input("请输入a"))
b = int(input("请输入b"))
c = a / b
print("商为:", c)
except ValueError:
print("数值错误,仅能接收整数参数")
except ArithmeticError:
print("算术错误")
except Exception:
print("未知错误")
```
比如输入的值不能支持变为整数时会报`ValueError`当除数为0的时候会报`ArithmeticError`等。
我们可以注意到有的时候异常处理结构可以结合循环语句进行在前面的例子中我们在except块仅做了日志打印处理在实际编程中这可能是还不够的。我们可以在异常捕获到之后如果错误的数据能修复的尝试进行修复将异常信息保存到一个日志文件中也可以在这一步发送邮件、短信等通知合适的运维人员等等。完成异常正确处理之后我们可以使用`continue`之类的语句控制进入下一次循环或者绕过这一条错误的条目。
### 单词释义
| 单词 | 释义 |
| --------------- | -------- |
| ValueError | 值错误 |
| ArithmeticError | 算术错误 |