r/AskProgramming • • 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

28 comments sorted by

View all comments

Show parent comment

2

u/ColoRadBro69 Jul 11 '26

You would use IF before you open a file to read its contents and not do that unless the file exists. 

You want TRY when you open the file because it could be locked at the OS level or it might have been deleted after your check ran.

1

u/SeriousPlankton2000 Jul 12 '26

You can only use "if" while opening the file, otherwise you get a race condition. (Or you're writing for MSDOS maybe?).

The stat() call done by if (… .exists()) has no real benefit. Just look at the error code.