Foundations introduced try / except in week 4. We're going deeper. The two-line shape:
try:
risky()
except SomeError:
handle()If risky() raises SomeError, control jumps to the except block. If it doesn't raise, the except block is skipped.
And if it raises a different error — not SomeError?
That error propagates as if no try/except was there. The except is type-specific.
Why match a specific type? Why not catch everything?
Three reasons:
except: swallows Ctrl-C. KeyboardInterrupt is an exception too — bare except catches it. Now you can't stop the script.except: hides bugs. A typo in a variable name raises NameError. If you catch everything, you mask the real problem.except FileNotFoundError: tells the reader "I expected the file might not exist and I handled it." except: tells them nothing.So today we open a file that probably doesn't exist and handle the failure gracefully?
Exactly that. open("nonexistent.txt") raises FileNotFoundError. We catch it, print "missing", move on.
try / except — the whole shapetry:
body() # might raise
except SpecificError:
handle_it() # only runs if SpecificError firedFlow:
body().except is skipped, execution continues after the whole block.SpecificError — handle_it() runs, then execution continues after the whole block.as to capture the errortry:
int("hello")
except ValueError as e:
print("parse failed:", e)
# parse failed: invalid literal for int() with base 10: 'hello'The as e binds the exception object to a name so you can inspect or log it. Useful for debug output.
# Bad — bare except
try:
do_thing()
except: # catches EVERYTHING including KeyboardInterrupt
pass
# Bad — except Exception with empty body
try:
do_thing()
except Exception:
pass # silently swallows all real errors
# Better — name what you expect
try:
do_thing()
except FileNotFoundError:
print("file not found, using defaults")if key in d: is clearer than try: d[key] except KeyError: for cases where the absence is expected.Open a file that doesn't exist. FileNotFoundError fires. Catch it, print "missing", move on. The script doesn't crash.
Foundations introduced try / except in week 4. We're going deeper. The two-line shape:
try:
risky()
except SomeError:
handle()If risky() raises SomeError, control jumps to the except block. If it doesn't raise, the except block is skipped.
And if it raises a different error — not SomeError?
That error propagates as if no try/except was there. The except is type-specific.
Why match a specific type? Why not catch everything?
Three reasons:
except: swallows Ctrl-C. KeyboardInterrupt is an exception too — bare except catches it. Now you can't stop the script.except: hides bugs. A typo in a variable name raises NameError. If you catch everything, you mask the real problem.except FileNotFoundError: tells the reader "I expected the file might not exist and I handled it." except: tells them nothing.So today we open a file that probably doesn't exist and handle the failure gracefully?
Exactly that. open("nonexistent.txt") raises FileNotFoundError. We catch it, print "missing", move on.
try / except — the whole shapetry:
body() # might raise
except SpecificError:
handle_it() # only runs if SpecificError firedFlow:
body().except is skipped, execution continues after the whole block.SpecificError — handle_it() runs, then execution continues after the whole block.as to capture the errortry:
int("hello")
except ValueError as e:
print("parse failed:", e)
# parse failed: invalid literal for int() with base 10: 'hello'The as e binds the exception object to a name so you can inspect or log it. Useful for debug output.
# Bad — bare except
try:
do_thing()
except: # catches EVERYTHING including KeyboardInterrupt
pass
# Bad — except Exception with empty body
try:
do_thing()
except Exception:
pass # silently swallows all real errors
# Better — name what you expect
try:
do_thing()
except FileNotFoundError:
print("file not found, using defaults")if key in d: is clearer than try: d[key] except KeyError: for cases where the absence is expected.Open a file that doesn't exist. FileNotFoundError fires. Catch it, print "missing", move on. The script doesn't crash.
Create a free account to get started. Paid plans unlock all tracks.