user49404
user49404

Reputation: 917

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.

import traceback

raise Exception('dogs')
# traceback.print_exc()

print('cat')

#=> Also doesn't print cat.

So what exactly is going on here? What is the difference between the traceback.print_exc() module and print()? I found it surprising that apparently some functions can run after the exception is raised, but not others.

Any thoughts appreciated.

Thanks.

Upvotes: 0

Views: 68

Answers (1)

bigbounty
bigbounty

Reputation: 17408

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

import traceback

try:
    raise Exception('dogs')
except:
    traceback.print_exc()
    print('cat')

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

Upvotes: 1

Related Questions