What happens when this runs?
pairs = [(10, 2), (8, 0), (15, 3)]
for a, b in pairs:
print(a / b)First iteration prints 5.0. Second one — divide by zero — crashes the whole script. Third one never runs.
Right. Python raises a ZeroDivisionError and stops. To keep going, you wrap the risky line in try and tell Python what to do except when it fails:
for a, b in pairs:
try:
print(a / b)
except ZeroDivisionError:
print("undefined")Now you get 5.0, undefined, 5.0. The script survives the bad case.
When should I use try/except?
When the error is something you can handle — a known shape (file missing, network down, key not in dict) where the right move is to log and continue, or fall back to a default. Don't wrap try/except around bugs — bugs should crash so you find them. Wrap it around expected failure modes: external systems flake, user input is wrong, data has gaps.
try / except — survive expected failurestry:
risky_thing()
except SomeError:
handle_it()If risky_thing() raises SomeError, control jumps to the except block. If no error, the except block is skipped.
try:
x = 10 / 0
except ZeroDivisionError:
print("can't divide by zero")| Error | When |
|---|---|
ZeroDivisionError | a / 0 |
KeyError | d["missing"] on a dict |
IndexError | lst[100] past the end |
ValueError | int("hello") — wrong shape input |
TypeError | "a" + 1 — wrong types |
FileNotFoundError | open("missing.txt") |
try:
int("hello")
except ValueError as e:
print("failed to parse:", e)
# failed to parse: invalid literal for int() with base 10: 'hello'The as e binds the error to a name so you can print or log it.
try:
do_thing()
except (ValueError, TypeError):
print("bad input")Or with separate handlers:
try:
do_thing()
except ValueError:
print("bad value")
except TypeError:
print("bad type")excepttry:
do_thing()
except: # ← catches EVERYTHING — even Ctrl-C
passBare except swallows all errors silently. You'll never see real bugs. Always name the error type. If you genuinely need to catch any non-system exception, use except Exception: — at least it leaves Ctrl-C alone.
if key in d: ... else: ... is clearer than try: d[key] except KeyError: ... for predictable cases.try / except / finally to always close a file or release a lock (later)What happens when this runs?
pairs = [(10, 2), (8, 0), (15, 3)]
for a, b in pairs:
print(a / b)First iteration prints 5.0. Second one — divide by zero — crashes the whole script. Third one never runs.
Right. Python raises a ZeroDivisionError and stops. To keep going, you wrap the risky line in try and tell Python what to do except when it fails:
for a, b in pairs:
try:
print(a / b)
except ZeroDivisionError:
print("undefined")Now you get 5.0, undefined, 5.0. The script survives the bad case.
When should I use try/except?
When the error is something you can handle — a known shape (file missing, network down, key not in dict) where the right move is to log and continue, or fall back to a default. Don't wrap try/except around bugs — bugs should crash so you find them. Wrap it around expected failure modes: external systems flake, user input is wrong, data has gaps.
try / except — survive expected failurestry:
risky_thing()
except SomeError:
handle_it()If risky_thing() raises SomeError, control jumps to the except block. If no error, the except block is skipped.
try:
x = 10 / 0
except ZeroDivisionError:
print("can't divide by zero")| Error | When |
|---|---|
ZeroDivisionError | a / 0 |
KeyError | d["missing"] on a dict |
IndexError | lst[100] past the end |
ValueError | int("hello") — wrong shape input |
TypeError | "a" + 1 — wrong types |
FileNotFoundError | open("missing.txt") |
try:
int("hello")
except ValueError as e:
print("failed to parse:", e)
# failed to parse: invalid literal for int() with base 10: 'hello'The as e binds the error to a name so you can print or log it.
try:
do_thing()
except (ValueError, TypeError):
print("bad input")Or with separate handlers:
try:
do_thing()
except ValueError:
print("bad value")
except TypeError:
print("bad type")excepttry:
do_thing()
except: # ← catches EVERYTHING — even Ctrl-C
passBare except swallows all errors silently. You'll never see real bugs. Always name the error type. If you genuinely need to catch any non-system exception, use except Exception: — at least it leaves Ctrl-C alone.
if key in d: ... else: ... is clearer than try: d[key] except KeyError: ... for predictable cases.try / except / finally to always close a file or release a lock (later)Create a free account to get started. Paid plans unlock all tracks.