Exception handling in python for multiple functions

4089 views python
-2

I have multiple functions calling which need to throw the same exceptions, i have created a decorator for this task so as to not repeat the exception handling code, but i would like to make this decorator generic so as to handle exceptions specified by user. I am attaching my sample code below.

def exception_decorator(func):
    def new_func(*args, **kwargs):
        try:
            ret = func(*args, **kwargs)
            return ret
        except OSError as e1:
            return str(e1)
        except ZeroDivisionError as e2:
            return str(e2)
        except ImportError as e3:
            return str(e3)
        except IOError as e4:
            return str(e4)
        except NameError as e5:
            return str(e5)
    return new_func


class Foo:
    def __init__(self):
        pass

    @exception_decorator
    def func1(self):
        return 1/0

    @exception_decorator
    def func2(self):
        f = open("filename","r")
        return "done"

    @exception_decorator
    def func3(self):
        return datetime.datetime.now()

obj = Foo()
print obj.func2()

I have hardcoded the list of exceptions in the decorator, i want the list of exceptions to be passed when applying the decorator and achieve the same behavior. Any ideas how this could be implemented. Also how do i make this decorator a class function instead of defining it outside the class? Thanks in advance for the help.

answered question

1 Answer

1

You can use a wrapper function that takes variable arguments of exceptions and returns a decorator:

def exception_decorator(*exceptions):
    def decorator(func):
        def new_func(*args, **kwargs):
            try:
                ret = func(*args, **kwargs)
                return ret
            except exceptions as e:
                return str(e)
        return new_func
    return decorator

so that:

import datetime
class Foo:
    def __init__(self):
        pass

    @exception_decorator(ZeroDivisionError)
    def func1(self):
        return 1/0

    @exception_decorator(IOError, OSError)
    def func2(self):
        f = open("filename","r")
        return "done"

    @exception_decorator(TypeError, ValueError)
    def func3(self):
        return datetime.datetime.strptime('2018/13/06', '%Y/%m/%d')

obj = Foo()
print obj.func1()
print obj.func2()
print obj.func3()

outputs:

integer division or modulo by zero
[Errno 2] No such file or directory: 'filename'
time data '2018/13/06' does not match format '%Y/%m/%d'

posted this

Have an answer?

JD

Please login first before posting an answer.