Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 373
Htechno Avatar asked Dec 12 '10 00:12

Htechno


People also ask

How do you handle a raise exception 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. We can thus choose what operations to perform once we have caught the exception.

Can we use raise without exception in Python?

Only an exception handler (or a function that a handler calls, directly or indirectly) can use raise without any expressions.

How do I manually raise exceptions?

Throwing exceptions manually There are two types of exceptions user defined and predefined each exception is represented by a class and which inherits the Throwable class. To throw an exception explicitly you need to instantiate the class of it and throw its object using the throw keyword.


1 Answers

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.

like image 85
Thomas K Avatar answered Sep 22 '22 00:09

Thomas K