Question

I'm using a PyQt4 user interface. I've redirected stderr to a log file for easy debugging and trouble-shooting, but now I need to display error messages to the user when an error occurs.

My issue is that I need to catch an exception when it happens and let the user know that it happened, but still let the traceback propagate to stderr (i.e. the log file).

If I do something like this:

def updateResults(self):
    try:
        #code that updates the results
    except:
        #display error message box

This will catch the exception and not propogate to the error log.

Is there some way to show the user the message and then continue to propogate the error?

Would this work?

except, e:
    #display error message box
    raise e

Is there a better way to accomplish my goal?

Was it helpful?

Solution

I think you are thinking about this in the wrong way. You shouldn't be re-raising the error simply to log it further down the line. The cannonical way of doing this in Python is to use the logging module. Adapted from the docs:

import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)

...

try:
    # code
except:
    logging.debug('Something bad happened', exc_info=True)
    # display message box
    # raise (if necessary)

This gives a far more flexible logging system than relying on errors produced on sys.stdout. You may not need to re-raise the exception if you can recover from the exception in some way.

OTHER TIPS

Exactly, but you can just

raise

which will re-raise the currently handled exception.

Some additional information:

(With PyQt4) you will also need to rebind sys.excepthook to your own function to catch all uncaught exceptions. Otherwise PyQt will just print them to the console, which may not be what you need...

import sys

def excepthook(exc_type, exc_val, tracebackobj):
    # do something useful with the uncaught exception
    ...

def main():
    # rebind excepthook
    sys.excepthook = excepthook
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top