在Python中,异常处理是应对程序运行时错误的一种机制。它能帮助我们捕获和处理错误,防止程序崩溃。下面是异常处理的关键知识和实践示例:
1. 异常处理基础
Python中的异常处理使用 try
, except
, else
, 和 finally
块来实现。
基本语法结构
try:# 可能发生异常的代码risky_code()
except ExceptionType as e:# 发生异常时执行的代码handle_exception(e)
else:# 未发生异常时执行的代码no_exception_occurred()
finally:# 无论是否发生异常都执行的代码cleanup()
2. 常见的异常类型
Exception
: 所有异常的基类。ValueError
: 函数接收到的参数类型不正确。IndexError
: 使用序列中不存在的索引。KeyError
: 使用映射中不存在的键。ZeroDivisionError
: 除数为零。
3. 使用 try
和 except
try
块包含可能产生异常的代码,而 except
块处理异常。
try:result = 10 / 0
except ZeroDivisionError as e:print(f"Error occurred: {e}")
4. 多个 except
块
你可以捕获不同类型的异常并分别处理。
try:with open("file.txt", "r") as file:content = file.read()
except FileNotFoundError:print("File not found.")
except IOError:print("An I/O error occurred.")
5. else
子句
else
块中的代码在没有异常发生时执行。
try:number = int(input("Enter a number: "))
except ValueError:print("That's not a valid number!")
else:print(f"The number is {number}")
6. finally
子句
finally
块总会执行,无论是否发生异常。通常用于清理操作。
try:file = open("file.txt", "r")content = file.read()
except FileNotFoundError:print("File not found.")
finally:if file:file.close()print("File has been closed.")
7. 自定义异常
你可以创建自己的异常,继承自内置的 Exception
类。
class CustomError(Exception):passdef risky_operation():raise CustomError("This is a custom error!")try:risky_operation()
except CustomError as e:print(f"Caught custom error: {e}")
8. 异常处理的最佳实践
- 仅捕获你能处理的异常。
- 保持
try
块中代码量最小,专注于可能出错的代码。 - 在适当的情况下使用
else
和finally
。
通过这些机制,异常处理不仅能够提高程序的稳定性,还能使代码更具可读性和可维护性。