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"
3
Upvotes
View all comments
Show parent comment
3
u/carcigenicate Jul 11 '26
Even simple, single threaded cases can cause problems. I'm more aware of TOCTOU bugs because I saw a one-in-a-million case first hand. In our codebase, we had code that looked roughly like this:
Where
cachewas a timednode-cachethat automatically invalidates cached entries after a period of time.I had the server running in debug mode with an exception breakpoint active, and actually caught this fail on the
obj.propline because the entry had expired between the condition and the access.In this case, the correct way to write this is to only call
getonce and save the result becausegetdoesn't throw on failure. If it did throw, though, atrywould have been the correct solution.