Friday 15 May 2015

Intercept specific exception module-wide in Python -



Intercept specific exception module-wide in Python -

i have defined custom exception need maintain track of , trigger process whenever thrown. enclose each line susceptible raise error in try-except pair, code grows, starts more , more ugly , cumbersome.

is there way create module-wide try-except statement?

tl;dr

i doing this:

class myerror(exception): pass try: #error-prone code except myerror: context_aware_function()

and looking this:

class myerror(exception): pass errormanager.redirect(from=myerror,to=context_aware_operation) #error-prone code

you intercept exceptions on per-function basis annotating them decorators. decorator implemented function takes function input , returns modified version of function. in case wrap input function try/except block:

def catch_error(function): def wrapper(*args, **kws): try: homecoming function(*args, **kws) except myerror: #handle error homecoming wrapper @catch_error def foo(): #error-prone code

python exception exception-handling

No comments:

Post a Comment