mike rodent
mike rodent

Reputation: 15642

Python: catch uncaught Exception but not exit immediately

from the standard library for sys module

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.

Is there any way of catching uncaught exceptions without necessarily immediately exiting thereafter (depending on a decision-making process)?

later
I suppose the answer is no. I suppose the BDFL, in his wisdom, offers this as a last-ditch opportunity to salvage a few crumbs from a collapsing, not-good program before it crumbles into oblivion leaving only a few logs behind.

Upvotes: 2

Views: 1546

Answers (1)

Obj3ctiv3_C_88
Obj3ctiv3_C_88

Reputation: 1528

Below except: acts as a catch all for any uncaught exception but this can have unexpected consequences. A better approach would be to write unit tests and proactively prepare for possible exceptions like a kid throwing unicode in a form.

try:
  # do something

except Exception_Type:
  # do something else

except:
  # woops didn't count on that

Upvotes: 1

Related Questions