Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch exceptions inside a class

Is it possible to write an exception handler to catch the run-time errors generated by ALL the methods in class? I can do it by surrounding each one with try/except:

class MyError(Exception):
    def __init__(self, obj, method):
        print 'Debug info:', repr(obj.data), method.__name__
        raise

class MyClass:
    def __init__(self, data):
        self.data = data

    def f1(self):
        try:
            all method code here, maybe failing at run time
        except:
            raise MyError(self, self.f1)

I wonder if is there a more general way to achieve the same - for any error raising anywhere in the class. I would like to be able to access the class data to print some debug info. Also, how do I get the failing method name (f1 in the example)?

Update: thanks to all for the insighful answers, the decorator idea looks like the way to go. About the risk of trapping ALL the exceptions: a raise statement in the except branch should re-raise the exception without losing any information, doesn't it? That's why I put it in MyError also...

like image 581
dave9000 Avatar asked Jul 10 '12 19:07

dave9000


People also ask

How do you catch all exceptions in a class in Python?

Try and Except Statement – Catching all Exceptions Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

How does Python handle exceptions in class?

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. We can thus choose what operations to perform once we have caught the exception.

Where exceptions are handled inside or outside?

Usually, the exception is caught inside the function and thrown from there so that it can be caught from where the function is called so that a proper remedy can be given depending on the parameters passed to the function. You can do both. When possible exceptions are few and simple, it doesn't much matter.

How do you raise an exception in a class in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.


1 Answers

Warning: if you want something like this, it's likely you don't... but if you really want to...

Something like:

import functools

def catch_exception(f):
    @functools.wraps(f)
    def func(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception as e:
            print 'Caught an exception in', f.__name__
    return func

class Test(object):
    def __init__(self, val):
        self.val = val

    @catch_exception
    def calc():
        return self.val / 0

t = Test(3)
t.calc()

shows how to decorate individual functions. You can then create a class decorator to apply this decorator to each method (be careful of classmethod's/staticmethod's/properties etc...)

like image 71
Jon Clements Avatar answered Oct 02 '22 00:10

Jon Clements