python generic exception handling and return arg on exception

Posted by rikAtee on Stack Overflow See other posts from Stack Overflow or by rikAtee
Published on 2012-11-03T22:50:17Z Indexed on 2012/11/03 23:00 UTC
Read the original article Hit count: 523

Filed under:
|

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()

© Stack Overflow or respective owner

Related posts about python

Related posts about exception-handling