Python异常处理:try/except语句的详细应用案例
在编程中,异常处理是一种机制,用于捕获和处理程序运行过程中的错误或未预期的情况。Python提供了try/except
语句来实现这一功能。
下面是一些详细的应用案例:
文件操作:
try:
f = open('non_existent_file.txt', 'r')
print(f.read())
except FileNotFoundError:
print("File not found.")
finally:
if 'f' in locals(): # 只有在try中,才需要处理文件
f.close()
网络请求:
try:
response = requests.get('http://example.com')
print(response.text)
except Exception as e:
print(f"Error: {str(e)})")
计算错误:
try:
result = 10 / 0 # 这会抛出一个ZeroDivisionError
print(result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
这些案例展示了如何使用try/except
语句来处理可能的异常情况。
还没有评论,来说两句吧...