What are ALL of the exceptions that pandas.read_csv() throw?

Viewed 8316

What are all the exceptions that can be thrown by pd.read_csv()?

In the example below I am capturing some exception types explicitly and using a generic Exception to catch the others, but what are the others exactly?

Reviewing the documentation for pandas read_csv() I can't see a complete list of exceptions thrown.

In a more general case, what is the recommended practice to determine all of the types of exceptions that can be thrown by any call/library?

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")
4 Answers

You can see all the exceptions in the following file:

Python > 3.8 > lib > python > site-packages > pandas > errors > __init__.py

BTW, the exceptions are:

  • IntCastingNaNError
  • NullFrequencyError
  • PerformanceWarning
  • UnsupportedFunctionCall
  • ParserError
  • DtypeWarning
  • EmptyDataError
  • ParserWarning
  • MergeError
  • AccessorRegistrationWarning
  • AbstractMethodError

A complete list and explanation can be found in the pandas source code

If you import pandas and use the dir function you can view all exceptions. Exceptions are contained in the pandas.errors submodule.

In [1]: import pandas as pd

In [2]: ([e for e in dir(pd.errors) if "__" not in e])
Out[2]: 
['AbstractMethodError',
'AccessorRegistrationWarning',
'DtypeWarning',
'DuplicateLabelError',
'EmptyDataError',
'IntCastingNaNError',
'InvalidIndexError',
'MergeError',
'NullFrequencyError',
'NumbaUtilError',
'OptionError',
'OutOfBoundsDatetime',
'OutOfBoundsTimedelta',
'ParserError',
'ParserWarning',
'PerformanceWarning',
'UnsortedIndexError',
'UnsupportedFunctionCall']

You can use these for exception handling. As an example, see below

import pandas as pd
import datetime

bad_date = datetime.date(22, 10, 4)

try:
    pd.to_datetime(bad_date)
except pd.errors.OutOfBoundsDatetime as e:
    # do some error handling here 
    # or raise the error
    print("there was a bad date")
    raise e

This is a way to catch all exceptions:

import sys

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

If you really want to find out the possible exceptions of read_csv you can look at the source code

Related