Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically catch exceptions in callback function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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.

>Solution :

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)

Outputs:

list index out of range error
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading