目录
简介
基本语法
捕获多个异常
自定义异常
简介
异常处理用于捕获和处理运行时错误,以确保程序的稳定性和可靠性。通过使用 try
、except
、else
和 finally
语句,可以控制错误的处理流程。
基本语法
try:# 可能引发异常的代码
except SomeException:# 处理异常的代码
else:# 如果没有异常,执行这部分
finally:# 无论是否发生异常,都会执行这部分
-
try 块:
- 包含可能引发异常的代码。
-
except 块:
- 用于捕获特定类型的异常。可以多个
except
处理不同的异常类型。
- 用于捕获特定类型的异常。可以多个
-
else 块:
- 当
try
块没有引发异常时执行。
- 当
-
finally 块:
- 无论是否发生异常,都会执行,适合用于清理资源(如文件关闭、数据库连接等)。
捕获多个异常
可以在一个 except
块中捕获多个异常:
try:# 可能引发多种异常的代码
except (ValueError, ZeroDivisionError) as e:print(f"Error occurred: {e}")
自定义异常
可以定义自己的异常类,通过继承 Exception
来创建自定义异常。
class InsufficientFundsError(Exception):"""异常类,用于处理余额不足的情况"""def __init__(self, balance, amount):super().__init__(f"Insufficient funds: Current balance is {balance}, attempted to withdraw {amount}.")self.balance = balanceself.amount = amountclass AccountClosedError(Exception):"""异常类,用于处理账户已关闭的情况"""def __init__(self, message="The account is closed."):super().__init__(message)class BankAccount:def __init__(self, initial_balance):self.balance = initial_balanceself.closed = Falsedef withdraw(self, amount):if self.closed:raise AccountClosedError()if amount > self.balance:raise InsufficientFundsError(self.balance, amount)self.balance -= amountreturn self.balancedef close_account(self):self.closed = True# 示例使用
try:account = BankAccount(100)account.withdraw(150) # 尝试提取超过余额的金额
except InsufficientFundsError as e:print(e)try:account.close_account() # 关闭账户account.withdraw(50) # 尝试在关闭账户后提取资金
except AccountClosedError as e:print(e)