Python Error Handling: try, catch, on, finally & assert
Robust Dart applications handle runtime failures using `try`, `on ExceptionType`, `catch (e, stackTrace)`, and `finally`. Dart distinguishes between **Exceptions** (intended to be caught and handled, like `FormatException` or `SocketException`) and **Errors** (program bugs like `RangeError`). `assert()` statements enforce invariants in development mode with zero production overhead.
"`try/catch` is like a trapeze safety net: you attempt a dangerous maneuver, and if you slip, the safety net catches you cleanly without halting the entire circus."
Deep Dive: How It Works
`on SpecificType`: Catches only designated exception subtypes without catching unrelated errors.
`catch (e, s)`: Binds the exception object `e` and the detailed execution `StackTrace s`.
`finally`: Block guaranteed to execute regardless of whether an exception occurred (ideal for closing streams/files).
`assert(expr, "message")`: Active only in debug mode; stripped out completely in AOT release builds.
Syntax Blueprint
try {
var num = int.parse("invalid");
} on FormatException catch (e) {
print("Invalid number: $e");
} catch (e, stackTrace) {
print("Unknown error: $e");
} finally {
print("Cleanup completed");
}Typed exception handling with fallback and guaranteed finalizer.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Catching `dynamic` and swallowing all errors silently without logging.Why it happens: Hides critical programming bugs (like `NoSuchMethodError` or `RangeError`).
How to fix: Catch specific exceptions with `on` and rethrow unexpected errors with `rethrow;`.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Catch FormatException Safely
Wrap `int.parse("not_a_number")` in a `try` block.
Catch `on FormatException` and print `Caught FormatException`.
Add a `finally` block that prints `Done`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.