Home > other >  Dynamically catch exceptions in callback function
Dynamically catch exceptions in callback function

Time:10-16

I'm writing a basic logging utility, and I want it to use a callback function, and then check for a list of exceptions that might have occurred.

I think the code will explain for itself.
I know the following example is not valid code, it is included for clarification.

    def Except(self, func, exceptions, *args, **kwargs):
        """Used for logging exceptions"""
        try:
            func(*args, **kwargs)
        for exception in exceptions: # Obviously this doesn't work.
            except exception as e:
                self.log(f"{e}", "error", 4)

However, I am surprised unpacking doesn't work.

    def Except(self, func, exceptions, *args, **kwargs):
        """Used for logging exceptions"""
        try:
            func(*args, **kwargs)
        except (*exceptions) as e:
            self.log(f"{e}", "error", 4)

Is there any way to dynamically catch exceptions with a callback function like this? I can't seem to find anything in the docs about it.

CodePudding user response:

You can create a custom Except class like this,

def Except(func, exceptions, *args, **kwargs):
    try:
        func(*args, **kwargs)
    except exceptions as e:
        print(f"{e}", "error")

def foo():
    l = [1]
    return l[1]
    
# Exception as tuple
exceptions = (TypeError, KeyError, IndexError)

Except(foo, exceptions)

Or, the most common approach catches the general exceptions.

try:
    foo()
except Exception as e:
    print(f"{e}", "error")

Outputs:

list index out of range error

CodePudding user response:

One way to solve this is to catch the general Exception exception, check if the actual exception belongs to the interesting exception classes and react accordingly.

This approach can also be used for a more individual reaction based on exception type. E. g. there could be a function assigned to each type which is called if the exception is of this type.

def Except(self, func, exceptions, *args, **kwargs):
    """Used for logging exceptions"""
    try:
        func(*args, **kwargs)
    except Exception as e:
        for ec in exceptions:
            if isinstance(e, ec):
                self.log(f"{e}", "error", 4)
                return
                
        raise
  • Related