Python中异常处理:案例演示
在Python编程中,异常处理是一种机制,用于处理程序运行时可能出现的错误。以下是一个简单的案例来说明如何使用异常处理。
假设我们有一个函数,它试图读取一个文件,但如果文件不存在,我们应该给用户提供有用的错误信息,而不是让程序崩溃。
def read_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"Error: File {file_path} not found.")
return None
except Exception as e:
print(f"An unexpected error occurred: {e}")
return None
# 测试代码
file_path = "non_existent_file.txt"
content = read_file(file_path)
if content is None:
print("File reading operation failed.")
在这个例子中,我们定义了一个read_file
函数,它尝试读取一个文件。如果文件不存在,我们会捕获FileNotFoundError
异常并打印友好的错误信息。这样可以确保程序在遇到错误时不会立即崩溃,而是能够提供有用的反馈给用户。
还没有评论,来说两句吧...