Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch an exception in a decorator but allow the caller to catch it as well?

Tags:

People also ask

How do I catch an exception and print message?

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.

What is catching exceptions in Python?

Catching Exceptions in Python 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.

How do decorators work in Python?

A decorator in Python is a function that takes another function as its argument, and returns yet another function . Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.

What is class decorator in Python?

Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.


I have a python function that may raise an exception. The caller catches the exception and deals with it. Now I would like to add a decorator to that function that also catches the exception, does some handling, but then re-raises the exception to allow the original caller to handle it. This works, except that when the original caller displays the call stack from the exception, it shows the line in the decorator where it was re-raised, not where it originally occurred. Example code:

import sys,traceback

def mydec(func):
    def dec():
        try:
            func()
        except Exception,e:
            print 'Decorator handled exception %s' % e
            raise e
    return dec

@mydec
def myfunc():
    x = 1/0

try:
    myfunc()
except Exception,e:
    print 'Exception: %s' % e
    type,value,tb = sys.exc_info()
    traceback.print_tb(tb)

The output is:

Decorator handled exception integer division or modulo by zero
Exception: integer division or modulo by zero
  File "allbug.py", line 20, in <module>
    myfunc()
  File "allbug.py", line 9, in dec
    raise e

I would like the decorator to be able to handle the exception but the traceback should indicate the x = 1/0 line rather than the raise line. How can I do this?