小编elm*_*tec的帖子

如何在Python中为异常添加上下文

我想为这样的异常添加上下文:

def process(vals):
    for key in vals:
        try:
            do_something(vals[key])
        except Exception as ex:  # base class. Not sure what to expect.
            raise # with context regarding the key that was being processed.
Run Code Online (Sandbox Code Playgroud)

我发现了一种对Python来说异常冗长的方式.有比这更好的方法吗?

try:
    do_something(vals[key])
except Exception as ex:
    args = list(ex.args)
    if len(args) > 1:
        args[0] = "{}: {}".format(key, args[0])
        ex.args = tuple(args)
    raise # Will re-trhow ValueError with new args[0]
Run Code Online (Sandbox Code Playgroud)

python exception

9
推荐指数
1
解决办法
1995
查看次数

标签 统计

exception ×1

python ×1