基础异常处理
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"除零错误: {e}")
except (TypeError, ValueError) as e:
print(f"类型或值错误: {e}")
except Exception as e:
print(f"其他错误: {e}")
else:
print("没有异常时执行")
finally:
print("总是执行")
区别: Python用except不用catch,可以用元组捕获多种异常,还有else块。
自定义异常
class InsufficientBalanceError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"余额不足: 当前{balance}元, 取出{amount}元")
class BankAccount:
def init(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientBalanceError(self.balance, amount)
self.balance -= amount
return self.balance
account = BankAccount(100)
try:
account.withdraw(200)
except InsufficientBalanceError as e:
print(e) # 余额不足: 当前100元, 取出200元
上下文管理器(with语句)
with open("data.txt", "r") as f:
content = f.read()
自动关闭文件
自定义上下文管理器
from contextlib import contextmanager
@contextmanager
def database_connection(url):
print(f"连接到 {url}")
conn = "模拟连接"
try:
yield conn
finally:
print("关闭连接")
with database_connection("mysql://localhost/db") as conn:
print(f"使用 {conn}")
pdb调试器
def complex_function(data):
result = []
for item in data:
processed = item.strip().lower()
breakpoint() # Python 3.7+ 自动启动pdb
if processed:
result.append(processed)
return result
常用命令: n(下一步), s(进入函数), c(继续), p var(打印变量), q(退出)
logging模块
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('app.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(name)
logger.info("一般信息")
logger.error("错误")
try:
1 / 0
except Exception as e:
logger.exception("除零错误") # 自动记录堆栈
最佳实践
# 不要吞掉异常
try:
do_something()
except Exception:
pass # BAD!
应该记录并处理
try:
do_something()
except Exception as e:
logger.error(f"处理失败: {e}")
raise # 或做恢复操作
总结
| 特性 | Python | Java |
|---|---|---|
| 检查型异常 | 没有 | 有 |
本系列持续更新中,关注不迷路。