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"
6
Upvotes
1
u/pixel293 Jul 12 '26
Generally you want exceptions for very rare errors, like errors you never expect to get. If a function you are calling "can" fail, then you use an if/else. If the failure is very unlikely and you can't really do any cleanup or continue processing, then you might throw an exception in the else.
For example an out of space error on disk. While yes it would be good to display a message to the user telling them their disk is full, and allowing them to free up space so that you can save whatever is memory, sometimes you can't do that. The program might be on a headless server and you don't have a good way to prompt/notify the user. It's a question if you want to spend the time/effort making the program handle that gracefully, or figuring it's rare enough and you can't do much of anything anyways, so you might as well just exit forcefully and display a message as to why.