在python dict.get()中引发异常

lup*_*ppa 0 python dictionary exception-handling

实际上,我已经知道我想做的事情有点奇怪,但是我认为它适合我的代码,所以我问:

有没有办法做这样的事情:

foo = { 'a':1, 'b':2, 'c':3 }
bar = { 'd':4, 'f':5, 'g':6 }

foo.get('h', bar.get('h'))
Run Code Online (Sandbox Code Playgroud)

引发异常而不是None,以防dict.get()失败?

foo.get('h', bar.get('h', raise)) 将提高 SyntaxError

foo.get('h', bar.get('h', Exception)) 只会回来 Exception

现在,我只是在和我一起工作,if not foo.get('h', bar.get('h')): raise Exception但是如果有直接提高筹码的方法,dict.get()我将非常高兴。

谢谢

小智 13

如果你想在 get 内部引发错误,那么你可以像这样欺骗:

{"a":4}.get("b", exec("raise Exception('some error msg') "))
Run Code Online (Sandbox Code Playgroud)

另外,如果您想避免拼写错误,请使用 f 字符串。


tho*_*747 5

使用下标,这是默认行为:

d={}
d['unknown key'] --> Raises a KeyError
Run Code Online (Sandbox Code Playgroud)

如果随后要引发自定义异常,则可以执行以下操作:

try:
    d['unknown key']
except KeyError:
    raise CustomException('Custom message')
Run Code Online (Sandbox Code Playgroud)

并包含KeyError中的stacktrace:

try:
    d['unknown key']
except KeyError as e:
    raise CustomException('Custom message') from e
Run Code Online (Sandbox Code Playgroud)