python-3.x - raise Exception("Something is wrong") 和 sys.exit("Something is wrong") 之间的区别
问题描述
我正在阅读高级同事的代码,他使用sys.exit("something is wrong")
了很多而不是raise Exception("something is wrong")
. 我做了一个快速测试:
sys.exit("something is wrong")
输出:
something is wrong
Process finished with exit code 1
raise Exception("something is wrong")
输出:
Traceback (most recent call last):
File "/Users/myname/gitlab/developer/my_developer/api.py", line 977, in <module>
raise Exception("something is wrong")
Exception: something is wrong
Process finished with exit code 1
在我看来,raise Exception("something is wrong")
提供的traceback
信息显示了该错误发生在哪一行,这对于缩小导致错误的行很有帮助。并在sys.exit("something is wrong")
其中仅打印了一条错误消息,而没有任何更多信息。对我来说raise Exception
似乎更有帮助,但我不确定我是否理解正确。谢谢
解决方案
这一切都取决于你在寻找什么。两者有非常不同的含义。
sys.exit('something is wrong') 将始终使用该消息退出程序。最终用户不必担心技术堆栈跟踪,这样会更干净。
raise Exception('Something is wrong') 将使用该消息引发异常。如果它未被捕获,它将退出程序并打印一个堆栈跟踪,允许程序员查看异常发生的原因,如果它在代码中被捕获,它允许程序员编写如果引发异常并且程序继续下一步应该发生的事情。
这完全取决于程序员想要做什么!
推荐阅读
- excel - Excel VBA 仅显示范围内具有空白单元格的行
- flutter - 多次使用 TextEditingController
- python - 将数据框行插入 SQL 数据库
- java - 如何从其他应用程序获取editText中的数据?
- google-sheets - 如何将每 50 行转换为 Google 表格中的列
- google-sheets - 如何使用非数字值的 vlookup
- c# - 为什么在 totalTimer 达到 +/- 300 后颜色停止变化?
- r - 如何在复杂调查中获得正确的频率表加权和未加权?
- java - 设置 Firestore 的最大用户数
- r - 将两个 ggplot 散点图与横断面作为原点相结合