pandas.read_csv() 抛出的所有异常是什么?

Mat*_*ttG 12 python dataframe pandas

pd.read_csv() 可能抛出哪些异常?

在下面的示例中,我显式捕获一些异常类型并使用通用异常来捕获其他异常类型,但其他异常类型到底是什么?

查看pandas read_csv() 的文档我看不到抛出的异常的完整列表。

在更一般的情况下,确定任何调用/库可能引发的所有异常类型的建议做法是什么?

import pandas as pd

try:
    df = pd.read_csv("myfile.csv")
except FileNotFoundError:
    print("File not found.")
except pd.errors.EmptyDataError:
    print("No data")
except pd.errors.ParserError:
    print("Parse error")
except Exception:
    print("Some other exception")
Run Code Online (Sandbox Code Playgroud)

小智 -8

这是捕获所有异常的一种方法:

import sys

try:
    int("test") # creates a ValueError
except BaseException as e:
    print('The exception: {}'.format(e))
Run Code Online (Sandbox Code Playgroud)

如果你真的想找出read_csv可能出现的异常,你可以查看源代码

  • https://realpython.com/the-most-diabolical-python-antipattern/ (6认同)
  • 这是一种非常糟糕的做法,您还会捕获不应该捕获的异常。 (2认同)