How does try/except work in Python?

Short answer

Put the risky code in try, and handle the specific exception in except. Always name the exception type — a bare except: swallows typos, keyboard interrupts and genuine bugs alike.

python
try:
    age = int(user_input)
except ValueError:
    print("That is not a whole number.")

#The full shape

python
try:
    data = load(path)
except FileNotFoundError:
    data = {}                  # a normal, expected case
except PermissionError as err:
    log(f"Cannot read {path}: {err}")
    raise                      # re-raise what you cannot handle
else:
    print("Loaded cleanly")    # runs only if no exception
finally:
    cleanup()                  # runs no matter what

else is the underused one: it holds code that should run only on success, without accidentally being covered by the try.

#Never write a bare except

python
try:
    risky()
except:              # catches EVERYTHING, including your own typos
    pass

That also catches KeyboardInterrupt (so Ctrl+C stops working) and SystemExit. If you truly need a catch-all, use except Exception:, which excludes those two.

Silently passing is worse still — it converts a crash you could debug into wrong behaviour you cannot.

#Catch narrowly

python
except (ValueError, TypeError) as err:
    ...

Catch the specific things you know how to handle. Anything else should propagate — a stack trace is far more useful than a program that quietly does the wrong thing.

#Ask forgiveness, not permission

Python style prefers trying and handling failure over checking first:

python
try:
    value = config["key"]
except KeyError:
    value = default

This avoids a race where the key disappears between the check and the access.