Exceptions
LockedLesson 13 of 60 · Debugging · Medium
Finish these first:Functions →Or pass the tests below to unlock it now.
The big idea
Handle errors with try / except / else / finally; raise with raise. Catch the narrowest exception you can; never use a bare except:.
Think of it like this: Think of debugging and error handling like a backup generator and circuit tester: `try/except` catches faults smoothly while tracing inputs reveals exactly where state diverged.
Read the lesson
Handle errors with try / except / else / finally; raise with raise.
try:
value = int(text)
except ValueError as e:
value = 0
else:
log("ok")
finally:
cleanup()
Catch the narrowest exception you can; never use a bare except:. Define custom errors by subclassing Exception.
Quick check
Before writing code: What should `safe_int('12')` return when your implementation of Exceptions is working?
Your challenge
Write safe_int(s, default=0) returning int(s) or default if it fails.
More learning tools(compare languages, visual guide, related lessons)
Compare with another language
Similar to javascript.error-handling (80% overlap). Error handling: try/catch in Python/Java/JS/C++ vs explicit (val, err) in Go and Result<T, E> in Rust.
Visual walkthrough
A diagram, a step-by-step animation, and short captions for Exceptions.
Learn this first
- FunctionsNot yet