Catch exceptions inside a class

后端 未结 3 890
别跟我提以往
别跟我提以往 2020-12-29 06:53

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:

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 07:25

    A decorator would be a good solution here.

    Here's an example of how you could do it:

    import inspect
    
    def catch_exception_decorator(function):
       def decorated_function:
          try:
             function()
          except:
             raise MyError(self.__class__, inspect.stack()[1][3])
       return decorated_function
    
    class MyClass(object):
        def __init__(self):
             ...
    
        @catch_exception_decorator
        def f1(self):
             ...
    

    @catch_exception_decorator on top of the function is a shortcut for f1 = catch_exception_decorator(f1).

    Instead of doing self.class, you could also access class data from the instance, as long as you're not shadowing variables. inspect.stack()[1][3] is the function name of the current function. You can use these to create the exception attributes.

提交回复
热议问题