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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With