1

I just started learning about Python Try Except even though I write program in Python for some time. I played with some examples of Python Try Except but for the current scenario, I was wondering if I can combine two Python Try Excepts. Here is an example of two individual Python Try Exceptions

First one:

try:
    df = pd.read_csv("test.csv")
except UnicodeDecodeError as error:
    print("UnicodeDEcodeErorr")

Second one:

try:
    df = pd.read_csv("test.csv", encoding = "ISO-8859-1")
except FileNotFoundError as fnf_error:
    print("File not found")

I can keep them as two separate Try Except but I was wondering if there is a way to combine them together.

upendra
  • 1,989
  • 9
  • 35
  • 57

2 Answers2

9

You can either combine them and keep their respective except control flows:

try:
    df = pd.read_csv("test.csv", encoding = "ISO-8859-1")
except FileNotFoundError as fnf_error:
    print("File not found")
except UnicodeDecodeError as error:
    print("UnicodeDEcodeErorr")

Or you can put the exceptions in a tuple and catch multiple exceptions:

try:
    df = pd.read_csv("test.csv", encoding = "ISO-8859-1")
except (FileNotFoundError, UnicodeDecodeError) as error:
    print("Do something else")
liamhawkins
  • 1,091
  • 2
  • 11
  • 27
1

You can add how many exceptions you want in tuple:

try:
    df = pd.read_csv("test.csv")
except (UnicodeDecodeError, FileNotFoundError) as error:
    print("UnicodeDEcodeErorr or FileNotFoundError")
Bulva
  • 1,148
  • 12
  • 27