Monday, 10 October 2016

How to combine two Python Try Exceptions




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.


Answer



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...