异常处理:Python中常见的错误和异常处理实例
在Python编程中,经常会遇到各种错误和异常。以下是一些常见错误和异常的处理实例:
- 除以零错误 (ZeroDivisionError)
try:
division = 10 / 2 # 正常执行
except ZeroDivisionError: # 处理异常
print("Error: Division by zero is not allowed.")
- 类型错误 (TypeError)
try:
string_number = "10" + 5 # 给定一个字符串和一个整数,试图合并它们
except TypeError: # 处理异常
print("Error: Mixed data types cannot be added.")
- 文件不存在错误 (FileNotFoundError)
try:
file_read = open("non_existent_file.txt", "r") # 尝试打开一个不存在的文件
except FileNotFoundError: # 处理异常
print("Error: File does not exist.")
finally:
if file_read: # 关闭文件,无论是否发生异常
file_read.close()
通过以上实例,你可以理解如何使用try/except块来处理Python中常见的错误和异常。
还没有评论,来说两句吧...