tl;dr
如何捕获相同类型但具有不同消息的不同异常?
情况
在理想世界中,我会处理这样的异常:
try:
do_something()
except ExceptionOne:
handle_exception_one()
except ExceptionTwo:
handle_exception_two()
except Exception as e:
print("Other exception: {}".format(e))
Run Code Online (Sandbox Code Playgroud)
但是我使用的外部代码在我的使用中可能会抛出两个异常。两者都是ValueError
s 但有不同的信息。我想区分处理它们。这是我尝试采用的方法(为了更容易地表达我提出的想法AssertionError
):
try:
assert 1 == 2, 'test'
except AssertionError('test'):
print("one")
except AssertionError('AssertionError: test'):
print("two")
except Exception as e:
print("Other exception: {}".format(e))
Run Code Online (Sandbox Code Playgroud)
但这段代码总是到最后print()
并给我
Other exception: test
Run Code Online (Sandbox Code Playgroud)
有没有办法以这种方式捕获异常?我假设这是可能的,因为 Python 允许我在捕获异常时指定 MESSAGE,ExceptionType('MESSAGE')
但实际上我没有设法让它工作。我也没有在文档中找到明确的答案。
我会去做这样的事情:
try:
do_the_thing()
except AssertionError as ae:
if "message A" in ae.value:
process_exception_for_message_A()
elif "message B" in ae.value:
process_exception_for_message_B()
else:
default_exception_precessing()
Run Code Online (Sandbox Code Playgroud)