使用特定的异常
捕获特定的异常类似于使用专门的工具来完成不同的任务。
捕获特定的异常类型至关重要,而不是依赖于通用的包罗万象的语句。
这种做法使你能够区分各种错误并提供准确的错误消息,从而更有效地识别和解决问题。
try:
# 可能引发特定异常的代码
...
except SpecificException as e:
# 处理特定异常
...
except AnotherSpecificException as e:
# 处理另一个特定异常
...
except Exception as e:
# 处理其他异常或提供后备行为
...
实际上用到的例子:
try:
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
# 对数据执行一些计算
result = int(row[0]) / int(row[1])
print(f"Result: {result}")
except FileNotFoundError:
print("The file 'data.csv' was not found.")
except IndexError:
print("Invalid data format in the CSV file.")
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid value encountered during calculations.")
except Exception as e:
print(f"An unexpected error occurred: {e}")