How does try/except work in Python?
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.
try:
age = int(user_input)
except ValueError:
print("That is not a whole number.")#The full shape
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 whatelse 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
try:
risky()
except: # catches EVERYTHING, including your own typos
passThat 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
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:
try:
value = config["key"]
except KeyError:
value = defaultThis avoids a race where the key disappears between the check and the access.