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

安稳与你 提交于 2019-11-26 11:06:21

问题


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.


回答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.




回答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.




回答3:


I'd suggest to not use the Exception mechanism to validate arguments, as tempting as that is. Coding with exceptions as conditionals is like saying, "crash my app if, as a developer, I don't think of all the bad conditions my provided arguments can cause. Perhaps using exceptions for things not only out of your control but also which is under control of something else like the OS or hardware or the Python language would be more logical, I don't know. In practice however I use exceptions as you request a solution for.

To answer your question, in part, it is just as simple to code thusly:

class MyObject(object):
    def saveas(self, filename):
        if not validate_filename(filename):
            return False
        ...

caller

if not myobject.saveas(filename): report_and_retry()

Perhaps not a great answer, just something to think about.



来源:https://stackoverflow.com/questions/4419785/dont-show-python-raise-line-in-the-exception-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!