r/AskProgramming • u/Excellent-Fan8457 • Jul 11 '26
When to use try/except vs if/else
I was making a simple program when I wondered when to use try and except this is the code I'm looking at.
if (Path.home() / "Desktop").exists():
desktop_path = Path.home() / "Desktop"
else:
desktop_path = Path.home() / "OneDrive/Desktop"
4
Upvotes
View all comments
Show parent comment
4
u/balefrost Jul 11 '26
It's tricky. Does a
FileNotFoundErrorrepresent an expected or unexpected situation? One can make a reasonable argument for either case.Some exceptions are truly panics. Others represent conditions that might or might not be expected, and should or should not be recovered from, and really it's up to the caller to decide which situation they're in.
Like from the caller's point of view, maybe they just created that file. So if they then try to open the file and the file doesn't exist (because of a race condition with something else that deleted the file), that's probably a fatal error, or at least not a locally-recoverable error.
On the other hand, if the caller is just trying to open say a settings file if it exists, then it's totally fine if the file doesn't exist.
The person writing the function to open the file can't know what kind of code will be calling it. Choosing to handle failure-as-exception will be "wrong" for some callers, and choosing to handle failure-as-data will be "wrong" for other callers.