首页 > 解决方案 > 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似乎更有帮助,但我不确定我是否理解正确。谢谢

标签: python-3.x

解决方案


这一切都取决于你在寻找什么。两者有非常不同的含义。
sys.exit('something is wrong') 将始终使用该消息退出程序。最终用户不必担心技术堆栈跟踪,这样会更干净。
raise Exception('Something is wrong') 将使用该消息引发异常。如果它未被捕获,它将退出程序并打印一个堆栈跟踪,允许程序员查看异常发生的原因,如果它在代码中被捕获,它允许程序员编写如果引发异常并且程序继续下一步应该发生的事情。
这完全取决于程序员想要做什么!


推荐阅读