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

1

u/pLeThOrAx Jul 11 '26
from pathlib import Path

home = Path.home()

if (home / "Desktop").is_dir():
    desktop_path = home / "Desktop"
else:
    desktop_path = home / "OneDrive" / "Desktop"
from pathlib import Path

home = Path.home()

candidates = [
    home / "Desktop",
    home / "OneDrive" / "Desktop",
]

desktop_path = next(
    (path for path in candidates if path.is_dir()),
    None,
)

if desktop_path is None:
    raise FileNotFoundError("Could not locate the Desktop directory.")