2

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
  • 2,141
  • 9
  • 39
  • 64

2 Answers2

11

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,301
  • 2
  • 12
  • 30
2

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,208
  • 14
  • 28