Python Errors and Exceptions
1. python中的try{}catch{}
2. raise exception
3. try...except ... else..
4. finally块
1. python中的try{}catch{}
python中的异常处理的关键字和c#中的是不相同的,python中使用try,except关键在来处理异常,如下:
def dive(x, y):
try:
result = x / y;
except ZeroDivisionError as z :
print("division by zero.", z);
else:
print("the result is ", result);
finally:
print("executing finally caluse.");
try:
result = x / y;
except ZeroDivisionError as z :
print("division by zero.", z);
else:
print("the result is ", result);
finally:
print("executing finally caluse.");
2. raise excepption
python中如果在except中如果需要将异常重新抛出可以使用关键字raise,类似于c#中的throw关键字。
def raise_test():
try:
result = 1 / 0;
except ZeroDivisionError :
print ("can not process the exception, to throw ...");
raise;
finally:
print("in finally block");
raise_test();
try:
result = 1 / 0;
except ZeroDivisionError :
print ("can not process the exception, to throw ...");
raise;
finally:
print("in finally block");
raise_test();
3. try...except ... else..
It is useful for code that must be executed if the try clause does not raise an exception
else块是说如果异常没有被抛出的情况下将被执行。
4. finally块
A finally clauseis always executed before leaving thetrystatement
finally块是一定会被执行的,不论异常是否产生。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?