martinez
martinez

Reputation: 63

Better way to write nested exceptions in Python

    try:
        return load(file)
    except FileNotFoundError:
        try:
            return load(otherfile)
        except FileNotFoundError:
            return None

How to write it more clean ? I feel there must be a better way to acomplish this (I assume there will be third file to load when other two will fail)

Upvotes: 0

Views: 114

Answers (1)

Artem Mashkovskiy
Artem Mashkovskiy

Reputation: 131

You can put it into the loop if you will have many files:

file_list = [file, otherfile]
for f in file_list:
    try:
        return load(f)
    except FileNotFoundError:
        continue
return None

Upvotes: 3

Related Questions