Hypercube
Hypercube

Reputation: 1193

Python everything in try block

I am writing a large batch-type script in Python, and need to do some cleanup in the end, regardless of whether an exception occurred. To do this I'm simply putting the main program in a try block and the cleanup in a finally block.

This seems to work well, but my question is how to print any exceptions that might occur. Currently it just ignores them and jumps to the finally block.

Upvotes: 0

Views: 344

Answers (2)

Ben
Ben

Reputation: 71535

You should just be able to use a try/finally block with no exception handler. It won't catch the exception or suppress the traceback, just ensure your cleanup code is run whether or not there is an exception. That's the entire point of finally.

Here's an example:

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
...     print 'begin try'
...     assert False
...     print 'end try'
... finally:
...     print 'finally'
... 
begin try
finally
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
AssertionError

Upvotes: 4

alampada
alampada

Reputation: 2409

you can use traceback.

something like:

import traceback
try:
    foo
except:
    print(traceback.format_exc())
finally:
     cleanup

Upvotes: 3

Related Questions