chiffa
chiffa

Reputation: 2088

Intercept specific exception module-wide in Python

I have defined a custom exception I need to keep track of and trigger a process whenever it is thrown. Currently I enclose each line that is susceptible to raise that error in a try-except pair, but as the code grows, this starts to look more and more ugly and cumbersome.

Is there a way to make a module-wide try-except statement?

tl;dr

I am currently doing this:

class MyError(exception):
   pass 

try:
   #error-prone code
except MyError:
   context_aware_function()

And I am looking for this:

class MyError(exception):
   pass 

errorManager.redirect(from=MyError,to=context_aware_operation)
#error-prone code

Upvotes: 2

Views: 352

Answers (1)

campkeith
campkeith

Reputation: 672

You could intercept exceptions on a per-function basis by annotating them with decorators. A decorator is implemented as a function that takes a function as input and returns a modified version of the function. In this case we wrap the input function with a try/except block:

def catch_error(function):
    def wrapper(*args, **kws):
        try:
            return function(*args, **kws)
        except MyError:
            #handle error
    return wrapper

@catch_error
def foo():
    #error-prone code

Upvotes: 2

Related Questions