0

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.

1
  • 1
    Show an example of your code. FYI, you do have to nest these blocks.
    – Keith
    Aug 31, 2011 at 23:36

2 Answers 2

4

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
2
  • This makes sense for most things, but in my program I need to catch and print the error before the finally block.
    – Hypercube
    Sep 1, 2011 at 0:19
  • Ah, that's kind of a different question then. The automatic traceback printing happens when an uncaught exception terminates the process. So what you needed was "How do I print a traceback for an exception I have caught?". finally is completely irrelevant to that.
    – Ben
    Sep 1, 2011 at 0:42
3

you can use traceback.

something like:

import traceback
try:
    foo
except:
    print(traceback.format_exc())
finally:
     cleanup
1
  • 2
    Why is it better than just try: foo finally: cleanup?
    – rczajka
    Aug 31, 2011 at 23:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.