我的代码有点像这样:
try:
# do stuff
except SomeSpecificException as sse:
if sse.some_property == some_special_value:
# handle the exception in a special way
else:
handle_exception_normally()
except:
handle_exception_normally()
我想捕获特定的异常并以特殊方式处理它,但前提是它具有特定属性。如果它没有该属性,我希望它可以像任何其他异常一样处理(记录,尖叫等)。
上面的代码有效,但如果可能的话,我希望避免重复handle_exception_normally()
(DRY以及所有这些。)
将raise
放在第一个else
块的except
子句中不起作用。父try
块会捕获它,但同一块中的catch-all子句不会。
我可以嵌套两个try
块,但它不是很优雅;我宁愿只是用
我上面的代码。
有更好的方法吗?
请注意,我使用的是Python 3。
答案 0 :(得分:5)
我会选择:
try:
# do stuff
except Exception as e:
if e.args[0] == 'Discriminate Exception Here' and sse.some_property == some_special_value:
# handle the exception in a special way
else:
handle_exception_normally()
建议
try:
# do stuff
except Exception as e:
if getattr(e, 'some_property', None) == some_special_value:
# handle the exception in a special way
else:
handle_exception_normally()
哪个更短,但要求some_special_value始终为!= None
,并且属性对您的例外而言是唯一的。
例外歧视的例子,e.args[0]
:
try:
5 / 0
except Exception as e:
print(e.args[0])
division by zero
使用__class__.__name__
:
try:
5 / 0
except Exception as e:
print(e.__class__.__name__)
ZeroDivisionError
使用isinstance()
(更多CPU密集型):
try:
5 / 0
except Exception as e:
isinstance(e, ZeroDivisionError)
True
答案 1 :(得分:0)
我理解OP说他们不想这样做,但我正在抛弃嵌套的try
块。我认为这是最可读的方式:
try:
try:
# do stuff
except SomeSpecificException as sse:
if sse.some_property == some_special_value:
# handle the exception in a special way
else:
raise
except:
handle_exception_normally()