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.

Hypercube
  • 1,181
  • 2
  • 10
  • 16

2 Answers2

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
Ben
  • 68,572
  • 20
  • 126
  • 174
  • This makes sense for most things, but in my program I need to catch and print the error before the finally block. – Hypercube Sep 01 '11 at 00: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 01 '11 at 00:42
3

you can use traceback.

something like:

import traceback
try:
    foo
except:
    print(traceback.format_exc())
finally:
     cleanup
alampada
  • 2,329
  • 1
  • 23
  • 18