无法捕获异常:发生了另一个异常

时间:2019-06-04 11:10:24

标签: python pandas exception index-error

我有以下代码:

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.

2 个答案:

答案 0 :(得分:0)

它被提出了。追溯提供有关前一个错误的信息,后者在后者期间得到了处理。由于您捕获了异常并引发了另一个异常,因此回溯信息将两者都包含在内。

它写在描述中: During handling of the above exception, another exception occurred:

您可以尝试引发另一种类型的错误,看看这是引发的错误。

答案 1 :(得分:0)

因为raise块中的except语句会强制一个新的异常来处理try块中发生的异常。 参见python documentation

相关问题