[英]How is the python traceback able to run after an exception has been raised?
I was surprised by the following behavior:我对以下行为感到惊讶:
import traceback
raise Exception('dogs')
traceback.print_exc()
print('cat')
#=> Successfully prints traceback, doesn't print cat. #=> 成功打印回溯,不打印 cat。
import traceback
raise Exception('dogs')
# traceback.print_exc()
print('cat')
#=> Also doesn't print cat. #=> 也不打印 cat。
So what exactly is going on here?那么这里到底发生了什么? What is the difference between the traceback.print_exc() module and print()? traceback.print_exc() 模块和 print() 有什么区别? I found it surprising that apparently some functions can run after the exception is raised, but not others.令我惊讶的是,一些函数显然可以在引发异常后运行,而其他函数则不能。
Any thoughts appreciated.任何想法表示赞赏。
Thanks.谢谢。
When an exception is raised, the control flow is changed.当引发异常时,控制流会发生变化。 Unless you catch the exception, all the statements below the line where exception was raised won't get executed.除非您捕获异常,否则引发异常的行下方的所有语句都不会执行。
Traceback is used to print stack traces - https://docs.python.org/3/library/traceback.html Traceback 用于打印堆栈跟踪 - https://docs.python.org/3/library/traceback.html
import traceback
try:
raise Exception('dogs')
except:
traceback.print_exc()
print('cat')
Output: Output:
In [5]: import traceback
...:
...: try:
...: raise Exception('dogs')
...: except:
...: traceback.print_exc()
...: print('cat')
...:
Traceback (most recent call last):
File "<ipython-input-5-3599c128a12e>", line 4, in <module>
raise Exception('dogs')
Exception: dogs
cat
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.