gpt4 book ai didi

python - 通用异常处理返回值

转载 作者:太空宇宙 更新时间:2023-11-04 10:52:04 24 4
gpt4 key购买 nike

我正在尝试创建通用异常处理程序 - 我可以在其中设置一个 arg 以在发生异常时返回。

而不是做:

try:
...
except Exception:
return list()

try:
...
except Exception:
return dict()

try:
...
except Exception:
return str()

我想创建一个系统,我有一个通用的异常处理程序,它返回我提供的 arg。例如,

def handler(code, default):
try:
code
except Exception:
return default

def mains():
code = <code to execute>
default = str()
return handler(code, dafault)

但以一种更pythonic的方式

最佳答案

一个简单的装饰器会为你做这件事。

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

一个简短的例子:

@catch_wrap('SPAM!')
def doer():
"""
YUP
"""
1 / 0
return 'EGGS!'


print doer()
print doer.__doc__

关于python - 通用异常处理返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13214377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com