我有以下代码:
import pandas as pd
index = 2
timestamps = pd.date_range('2019-05-01', '2019-05-01')
try:
timestamp = timestamps[index]
except IndexError:
raise IndexError('index is out of timestamps.')
导致将以下内容打印到终端上
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/datetimes.py", line 1170, in __getitem__
result = self._data.__getitem__(key)
File "/usr/local/lib/python3.7/site-packages/pandas/core/arrays/datetimelike.py", line 426, in __getitem__
val = getitem(key)
IndexError: index 2 is out of bounds for axis 0 with size 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
IndexError: index is out of timestamps.
请问为什么在这种情况下根本不提出IndexError: index is out of timestamps.
?
答案 0 :(得分:0)
它被提出了。追溯提供有关前一个错误的信息,后者在后者期间得到了处理。由于您捕获了异常并引发了另一个异常,因此回溯信息将两者都包含在内。
它写在描述中:
During handling of the above exception, another exception occurred:
您可以尝试引发另一种类型的错误,看看这是引发的错误。
答案 1 :(得分:0)
因为raise
块中的except
语句会强制一个新的异常来处理try
块中发生的异常。
参见python documentation