Python中处理异常的核心是try-except-else-finally结构,用于捕获和处理运行时错误,提升程序健壮性。try块包含可能出错的代码,except捕获特定异常,else在无异常时执行,finally无论是否发生异常都会执行,常用于资源清理。常见误区包括:过度捕获Exception导致问题被掩盖、空except块隐藏错误、滥用异常控制流程、忽略资源释放。应使用with语句管理资源,避免泄露。自定义异常需继承Exception类,用于表示特定业务错误,如余额不足;通过raise主动抛出异常,适用于参数校验失败、状态不满足等情况;在except中可使用raise重新抛出异常,或用raise ... from ...建立异常链,明确错误因果关系,增强调试能力。合理设计异常处理可提高代码可读性、可维护性和系统可靠性。

Python中处理异常的核心机制是
try-except
在Python中,异常处理主要围绕着
try
except
else
finally
try
try
except
except
try
try
as e
立即学习“Python免费学习笔记(深入)”;
else
try
try
finally
try
except
finally
try-except
else
finally
一个基本的例子是这样的:
try:
# 尝试执行一些可能出错的代码
num = int(input("请输入一个整数:"))
result = 10 / num
print(f"结果是: {result}")
except ValueError:
# 如果用户输入了非整数
print("输入无效,请输入一个有效的整数。")
except ZeroDivisionError:
# 如果用户输入了0
print("除数不能为零!")
except Exception as e:
# 捕获所有其他类型的异常
print(f"发生了未知错误: {e}")
else:
# 如果try块没有异常,这里会执行
print("操作成功完成,没有发生任何异常。")
finally:
# 无论如何,这里都会执行
print("程序执行结束。")这个结构提供了一种优雅的方式来应对各种预料之中和预料之外的问题,让程序能够从容地处理错误,而不是直接崩溃。
当我们谈论Python异常处理的基本结构时,前面提到的
try-except-else-finally
try
except
finally
else
基本结构再强调一下:
try
except [ExceptionType [as name]]
except
ExceptionType
else
try
finally
try
常见误区:
Exception
except Exception as e:
TypeError
FileNotFoundError
except
except
try-except
if not my_list:
try-except
finally
with
# 避免捕获过于宽泛的Exception
try:
file = open("non_existent_file.txt", "r")
except FileNotFoundError:
print("错误:文件未找到。")
except PermissionError:
print("错误:没有权限访问文件。")
except IOError as e: # 捕获其他I/O错误
print(f"发生I/O错误: {e}")
# else: # 如果有需要,可以添加else
# finally: # 如果有需要,可以添加finally正确识别并避免这些误区,能让我们的异常处理代码更加健壮和高效。
有时候,Python内置的异常类型不足以精确描述我们程序中特有的错误情况。这时,自定义异常就显得尤为重要。它能让我们的代码更具表现力,也方便其他开发者理解错误发生的具体上下文。
如何自定义异常: 在Python中,自定义异常非常简单,只需要创建一个新的类,并让它继承自
Exception
ValueError
TypeError
class InsufficientFundsError(Exception):
"""自定义异常:余额不足错误"""
def __init__(self, message="账户余额不足,无法完成操作。", current_balance=0, required_amount=0):
super().__init__(message)
self.current_balance = current_balance
self.required_amount = required_amount
def __str__(self):
return f"{self.args[0]} 当前余额: {self.current_balance}, 需要金额: {self.required_amount}"
# 使用自定义异常
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(
message="提款失败",
current_balance=balance,
required_amount=amount
)
return balance - amount
try:
current_account_balance = 100
new_balance = withdraw(current_account_balance, 150)
print(f"提款成功,新余额: {new_balance}")
except InsufficientFundsError as e:
print(f"处理提款失败: {e}")
print(f"详细信息 - 当前余额: {e.current_balance}, 需求金额: {e.required_amount}")通过继承
Exception
何时应该主动抛出(raise
raise
withdraw
InsufficientFundsError
except
except
raise
try:
# 某些操作
pass
except SomeSpecificError:
print("记录日志:发生了特定错误。")
raise # 重新抛出当前异常raise from
raise ... from ...
def process_data(data_source):
try:
# 尝试从数据源读取数据,可能引发IOError
with open(data_source, 'r') as f:
content = f.read()
# 进一步处理内容,可能引发ValueError
if not content.strip():
raise ValueError("数据源内容为空。")
except FileNotFoundError as e:
# 文件找不到,但我们想抛出一个更高级别的DataProcessingError
raise DataProcessingError(f"无法找到数据源: {data_source}") from e
except ValueError as e:
raise DataProcessingError(f"数据处理失败: 无效内容") from e这里,
DataProcessingError
FileNotFoundError
ValueError
from e
通过自定义异常和合理使用
raise
以上就是Python中异常怎么处理 Python中异常处理详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号