2

I have a function called onError(). When it is ran, it prints "There was an error"

I want this function to run whenever an error occurs, for example, if I raise NameError, the function runs.

Here is my code

def onError():
    print("There was an error")

raise NameError

I know that try and except exist, but I want a way to do it without them.

1 Answers1

6

You can define a "global" exception handler by overriding sys.excepthook.

Here's an example.

import sys

def onError(exception_type, value, traceback):
    print("There was an error")

sys.excepthook = onError
Leo
  • 1,273
  • 9
  • 14