调试Python代码时遇到的常见异常处理
在调试Python代码时,可能会遇到各种异常。这里列出一些常见的异常类型以及如何进行异常处理:
TypeError:当函数或方法接收到不匹配类型的参数时,会抛出这个错误。
def add(a, b):
return a + b
try:
result = add(2, "3"))
except TypeError as e:
print(f"TypeError: {e}")
# 输出:TypeError: can only concatenate str (not "int") to str
ValueError:当函数或方法接收到的参数不符合预期时,会抛出这个错误。
def validate_age(age):
if not isinstance(age, int) or age < 0:
raise ValueError("Invalid age: must be a non-negative integer.")
try:
validate_age(-5)
except ValueError as e:
print(f"ValueError: {e}")
# 输出:ValueError: Invalid age: must be a non-negative integer.
FileNotFoundError:当尝试打开一个文件,但该文件不存在时,会抛出这个异常。
try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError as e:
print(f"FileNotFoundError: {e}")
# 输出:FileNotFoundError: [Errno 2] No such file or directory: 'non_existent_file.txt'
在编写代码时,通常会使用try/except
语句来捕获和处理这些异常。
还没有评论,来说两句吧...