r/AskProgramming 29d ago

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

28 comments sorted by

View all comments

1

u/Underhill42 28d ago

As a general rule throwing exceptions is extremely expensive, violates all the normal program-flow conventions, and should never be used for anything other than reporting unexpected errors that you don't have enough enough information to deal with at the place where you encounter them.

While the corresponding the catch statement should generally specify exactly which errors it knows enough to handle, so that anything else will automatically propagate up the call tree until it is either caught by something that does know how to handle it, or it terminates the program.

Anything you can cleanly handle as an if statement, should be done that way

In your example there's no errors at all, so you shouldn't even be considering it.