Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic catch for python

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.

like image 325
Staale Avatar asked Jan 14 '09 09:01

Staale


People also ask

How do you catch a general exception in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

Is there a catch in Python?

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.

Does BaseException catch all exceptions?

The difference between catching Exception and BaseException is that according to the exception hierarchy exception like SystemExit, KeyboardInterrupt and GeneratorExit will not be caught when using except Exception because they inherit directly from BaseException .

Do we have try catch in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.


1 Answers

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: 
like image 144
nosklo Avatar answered Sep 21 '22 13:09

nosklo