Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic exception handling and return arg on exception

I am trying to create generic exception handler - for where I can set an arg to return in case of exception, inspired from this answer.

import contextlib


@contextlib.contextmanager
def handler(default):
    try:
        yield
    except Exception as e:
        yield default


def main():
    with handler(0):
        return 1 / 0

    with handler(0):
        return 100 / 0

    with handler(0):
        return 'helllo + 'cheese'

But this results in

RuntimeError: generator didn't stop after throw()
like image 351
Django Doctor Avatar asked Dec 06 '25 12:12

Django Doctor


1 Answers

The main conceptual problem is that you try to make the calling function implicitly return a value from within a called function. To give an example, what you are trying to do is coneptually equivalent to this situation:

def f():
    # some magic code here

def g():
    f()

And now you want the magic code to make g() return some value. This is never going to work.

Context managers are the wrong tool for this purpose. Consider using a decorator instead.

like image 197
Sven Marnach Avatar answered Dec 08 '25 00:12

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!