简体   繁体   English

在引发异常后,python 回溯如何运行?

[英]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.

相关问题 如何检测是否从python中的try块引发了异常? - How to detect if an exception has been raised from a try block in python? Python 仅打印引发异常的回溯 - Python only print traceback of raised exception Python自定义Exception类应该允许在引发程序后继续执行它 - Python customized Exception class should allow to continue the program execution after it has been raised 是否有可能在python中跟踪已引发的异常? - Is it possible in python to track exception raised even it has been caught? 引发异常后如何留在cmd窗口中? - How to stay in the cmd window when the exception has been raised? 在Python中引发错误后,如何在数据框中正确标记损坏的数据表 - How to properly tag corrupted datalines in dataframe after an error has been raised in Python 测试初始化​​程序中是否引发了异常 - Test that the exception has been raised within initializer Python:如何在捕获到异常后停止执行? - Python : How to stop execution after exception has been caught? 运行代码后如何禁用/限制一行代码? (蟒蛇) - How to disable/restrict a line of code after it has been run? (Python) 在 Python 提示符处引发错误后如何获取最后一个异常对象? - How to get the last exception object after an error is raised at a Python prompt?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM