问题
I am trying to create generic exception handler - for where I can set an arg to return in case of exception.
instead of doing:
try:
...
except Exception:
return list()
try:
...
except Exception:
return dict()
try:
...
except Exception:
return str()
I would like to create system whereby I have a generic exception handler that returns an arg I provide. e.g,
def handler(code, default):
try:
code
except Exception:
return default
def mains():
code = <code to execute>
default = str()
return handler(code, dafault)
but in a more pythonic way
回答1:
A simple decorator will do this for you.
import functools
def catch_wrap(on_err):
def wrapper(func):
@functools.wraps(func)
def inner(*args, **kw):
try:
return func(*args, **kw)
except Exception:
return on_err
return inner
return wrapper
A short example:
@catch_wrap('SPAM!')
def doer():
"""
YUP
"""
1 / 0
return 'EGGS!'
print doer()
print doer.__doc__
来源:https://stackoverflow.com/questions/13214377/generic-exception-handling-return-value