Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring Python's default exception handling

Tags:

python

For an uncaught exception, Python by default prints a stack trace, the exception itself, and terminates. Is anybody aware of a way to tailor this behaviour on the program level (other than establishing my own global, catch-all exception handler), so that the stack trace is omitted? I would like to toggle in my app whether the stack trace is printed or not.

like image 204
ThomasH Avatar asked Oct 21 '09 10:10

ThomasH


People also ask

How does Python handle default exceptions?

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.


1 Answers

You are looking for sys.excepthook:

sys.excepthook(type, value, traceback)

This function prints out a given traceback and exception to sys.stderr.

When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.

like image 141
Philippe F Avatar answered Oct 04 '22 21:10

Philippe F