捕捉 Numpy All-Nan 切片
Catching Numpy All-Nan Slice
我在尝试捕获 Python 异常时遇到问题:
File "/usr/lib/python2.7/dist-packages/numpy/lib/nanfunctions.py",
line 427, in nanargmax
raise ValueError("All-NaN slice encountered") ValueError: All-NaN slice encountered
当切片实际上包含 All-NaN 时,此代码会出现错误。但是,我想抓住这种情况并加以处理。
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
action = np.nanargmax(self.Q[state])
except Warning as e:
print "error"
sys.exit(0)
我希望打印单词error,然而try-except 语句被忽略了。有什么帮助吗?
您应该将 except Warning as e
更改为 except ValueError as e
。
这是因为 ValueError
class 不是 Warning
class 的子 class。或者,您可以使用 except Exception as e
捕获任何 Exception
,因为所有异常都是 Exception
class 的子 class,但最佳做法是尽可能精确有可能,但您发现了例外情况。
我在尝试捕获 Python 异常时遇到问题:
File "/usr/lib/python2.7/dist-packages/numpy/lib/nanfunctions.py", line 427, in nanargmax raise ValueError("All-NaN slice encountered") ValueError: All-NaN slice encountered
当切片实际上包含 All-NaN 时,此代码会出现错误。但是,我想抓住这种情况并加以处理。
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
action = np.nanargmax(self.Q[state])
except Warning as e:
print "error"
sys.exit(0)
我希望打印单词error,然而try-except 语句被忽略了。有什么帮助吗?
您应该将 except Warning as e
更改为 except ValueError as e
。
这是因为 ValueError
class 不是 Warning
class 的子 class。或者,您可以使用 except Exception as e
捕获任何 Exception
,因为所有异常都是 Exception
class 的子 class,但最佳做法是尽可能精确有可能,但您发现了例外情况。