115

I have some extremely weird behavior that seems to result in silent exceptions. How can I write a general try catch where I can debug all exceptions. Something along the lines of:

try:
    # something that fails
except e:
    print e

A bit more about the problem at hand in detail:

I have a Django app that on my computer (Ubuntu Linux 8.10) works fine both through runserver and mod-python. On the deploy server (Ubuntu Linux 8.10) it works fine through runserver, but fails via apache in mod-python.

I have reduced the cause down to a part off the app that uses Berkeley DB (bsddb.db), and secondary keys. The callback method for secondary keys uses pickle to format the keys. It fails when I call pickle on a single value. However, it only fails when I use cPickle, and using pickle on the same values outside the callback function also works.

I just want to know why it fails with cPickle.

3 Answers 3

220

Exceptions are already printed by default before program termination. If you want to send the error somewhere else (not print it) you can do this:

try:
    something()
except Exception as e:
    send_somewhere(traceback.format_exception(*sys.exc_info()))
    raise # reraises the exception

note that this format using the as keyword is for python > 2.6. The old way was:

except Exception, e:
Sign up to request clarification or add additional context in comments.

2 Comments

didn't know about the "Exception as e" change. "Exception, e" always bugged me, nice to see it got cleaned up.
'as' keyword is for python >= 2.6
5

The traceback module is quite useful for formatting tracebacks. You can then write it to a logfile.

Comments

2

Does this work? :

except BaseException, e:

1 Comment

You shouldn't catch BaseException - it includes SystemExit and KeyboardInterrupt, things you usually don't want to catch.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.