Don't show Python raise-line in the exception stack

When I raise my owns exceptions in my Python libraries, the exception stack shows the raise-line itself as the last item of the stack. This is obviously not an error, is conceptually right, but points the focus on something that is not useful for debugging when you're are using code externally, for example as a module.

Is there a way to avoid this and force Python to show the previous-to-last stack item as the last one, like the standard Python libraries.


Solution 1:

Due warning: modifying the behaviour of the interpreter is generally frowned upon. And in any case, seeing exactly where an error was raised may be helpful in debugging, especially if a function can raise an error for several different reasons.

If you use the traceback module, and replace sys.excepthook with a custom function, it's probably possible to do this. But making the change will affect error display for the entire program, not just your module, so is probably not recommended.

You could also look at putting code in try/except blocks, then modifying the error and re-raising it. But your time is probably better spent making unexpected errors unlikely, and writing informative error messages for those that could arise.

Solution 2:

you can create your own exception hook in python. below is the example of code that i am using.

import sys
import traceback

def exceptionHandler(got_exception_type, got_exception, got_traceback):
    listing  = traceback.format_exception(got_exception_type, got_exception, got_traceback)
    # Removing the listing of statement raise (raise line). 
    del listing[-2]
    filelist = ["org.python.pydev"] # avoiding the debuger modules.
    listing = [ item for item in listing if len([f for f in filelist if f in item]) == 0 ]
    files = [line for line in listing if line.startswith("  File")]
    if len(files) == 1:
        # only one file, remove the header.
        del listing[0]
    print>>sys.stderr, "".join(listing)

And below are some lines that I have used in my custom exception code.

sys.excepthook = exceptionHandler
raise Exception("My Custom error message.")

In the method exception you can add file names or module names in list "filenames" if you want to ignore any unwanted files. As I have ignored the python pydev module since I am using pydev debugger in eclipse.

The above is used in my own module for a specific purpose. you can modify and use it for your modules.