我处理数据,在某些示例中,数据有问题。 Python引发了一个
ValueError:残差在初始点不是有限的。
是否有可能仅通过消息"Residuals are not finite in the initial point."
来捕获Value错误?
我尝试过:
try:
[code that could raise the error]
except Exception as e:
if e=='ValueError(\'Residuals are not finite in the initial point.\')':
[do stuff I want when the Residuals are not finite]
else:
raise e
但是它仍然一直在引发错误。有没有办法实现我的想象?
谢谢
答案 0 :(得分:3)
try:
[code that could raise the error]
except ValueError as e:
if len(e.args) > 0 and e.args[0] == 'Residuals are not finite in the initial point.':
[do stuff I want when the Residuals are not finite]
else:
raise e
您可能必须检查e.args[0]
是否完全包含此字符串(引发错误并打印e.args[0]
)
答案 1 :(得分:-2)
您可以像这样捕获ValueError异常:
try:
#[code that could raise the error]
except ValueError as e:
print("Residuals are not finite in the initial point. ...")
#[do stuff I want when the Residuals are not finite]