异常处理:区分 Python 中相同错误的实例
Exception handling: Differentiating between instances of the same error in Python
根据引起异常的原因不同,相同类型的异常分别处理的推荐方法是什么?
假设一个人希望以不同方式处理 AttributeError
的以下两个实例:
'str' object has no attribute 'append'
'float' object has no attribute 'append'
同时,我们不想处理其他属性错误。
是否有适用于所有异常类型的通用答案?我可以使用异常对象上的某些方法或函数来查询异常对象的详细信息吗?
Try:
blah
Except AttributeError as exc:
if exc.baz('foo') is bar:
handle 'str' object has no attribute 'append'
elif plugh(exc):
handle 'float' object has no attribute 'append'
else:
raise exc
我认为显而易见的答案是重构。我的问题特别针对效率低下或根本不可能的情况(如果有任何此类情况)。
你可以通过dir
.
查看一个对象有哪些方法和属性
在 Python 3.6 中,来自:
a = 'hello'
try:
a.append(2)
except AttributeError as e:
print(dir(e))
你得到:
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'with_traceback']
这缩小了我们可以测试的范围,因为我们不想要双打,只留下 args
和 with_traceback
。看来你能得到的最好的方法是使用 args
其中 returns 元组中的字符串:
a = 'hello'
try:
a.append(2)
except AttributeError as e:
if 'str' in e.args[0]:
print('Need to handle string')
elif 'float' in e.args[0]:
print('Need to handle float')
根据引起异常的原因不同,相同类型的异常分别处理的推荐方法是什么?
假设一个人希望以不同方式处理 AttributeError
的以下两个实例:
'str' object has no attribute 'append'
'float' object has no attribute 'append'
同时,我们不想处理其他属性错误。
是否有适用于所有异常类型的通用答案?我可以使用异常对象上的某些方法或函数来查询异常对象的详细信息吗?
Try:
blah
Except AttributeError as exc:
if exc.baz('foo') is bar:
handle 'str' object has no attribute 'append'
elif plugh(exc):
handle 'float' object has no attribute 'append'
else:
raise exc
我认为显而易见的答案是重构。我的问题特别针对效率低下或根本不可能的情况(如果有任何此类情况)。
你可以通过dir
.
在 Python 3.6 中,来自:
a = 'hello'
try:
a.append(2)
except AttributeError as e:
print(dir(e))
你得到:
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'with_traceback']
这缩小了我们可以测试的范围,因为我们不想要双打,只留下 args
和 with_traceback
。看来你能得到的最好的方法是使用 args
其中 returns 元组中的字符串:
a = 'hello'
try:
a.append(2)
except AttributeError as e:
if 'str' in e.args[0]:
print('Need to handle string')
elif 'float' in e.args[0]:
print('Need to handle float')