ToolkitX
知识库工具箱

异常处理

try/except、自定义异常、上下文管理器

20min·进阶

01. try/except 基础

Python 使用 try/except 来捕获和处理异常。try 块中放置可能出错的代码,except 块处理异常。
python
# 基本语法
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")

# 捕获多个异常
try:
num = int(input("请输入数字: "))
except ValueError:
print("输入的不是有效数字")
except ZeroDivisionError:
print("不能除以零!")

# else 和 finally
try:
f = open("data.txt", "r")
except FileNotFoundError:
print("文件不存在")
else:
content = f.read()
finally:
  print("清理工作完成")

02. 自定义异常

可以通过继承 Exception 类创建自定义异常,使错误处理更具语义化。
python
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
    self.balance = balance
    self.amount = amount
    super().__init__(f"余额不足: 当前 {balance}, 需要 {amount}")

def withdraw(balance, amount):
if amount > balance:
    raise InsufficientFundsError(balance, amount)
return balance - amount

try:
new_balance = withdraw(100, 200)
except InsufficientFundsError as e:
  print(e)

知识测验

1/5正确 0

try/except/finally 中 finally 什么时候执行?

下一节

正则表达式

下一节