I'm choosing between a Desktop folder under my home directory and one under OneDrive. Should I check whether the first path exists with if/else, or use try/except instead?
Should I use try/except or if/else to check a file path?
Answers
For choosing between candidates, an if/else is a reasonable way to express the decision. Use Path.is_dir() if you need a directory rather than just any existing path. Also check the fallback instead of assuming it exists.
Creating a Path object doesn't check the filesystem, so wrapping just that in try/except won't tell you whether the folder is usable.
Reply to this answer
The check doesn't guarantee the later operation will work. A folder can disappear or its permissions can change between checking it and using it. Put the operation that actually opens or writes the file in a try block and handle the errors you can meaningfully recover from.
For example, catch FileNotFoundError if a missing folder should trigger a fallback. A PermissionError is a different problem, so decide separately whether that should also trigger a fallback or be reported. Keep the try block narrow and avoid catching every exception just to move on.
Reply to this answer
There's a separate issue here: neither location is guaranteed to be the user's actual Desktop. Both could exist, or the Desktop could be somewhere else entirely.
If this is for Windows and you need the configured Desktop, look into the Windows known folder API, specifically SHGetKnownFolderPath with FOLDERID_Desktop. Checking a couple of guessed paths is only a heuristic.
Reply to this answer
I wouldn't make a hard rule that exceptions are only for unexpected events. A missing file might be normal for one program and a serious problem for another. The useful question is whether the operation raises an exception and whether your code has a sensible response to it.
Reply to this answer
Add your answer
Answers are reviewed before publication.
saffronless-kiosk:
That can still matter even if you're not using threads. Another program could change the directory between the check and the operation.