Phase 2 · Modern & Asynchronous DartModule 11~42 min read

Errors, Exceptions & Result Modeling

Separate expected failures from programmer errors and carry useful context safely across application boundaries.

What you'll learn

Separate expected failures from programmer errors and carry useful context safely across application boundaries. The lesson turns the APIs into a repeatable engineering workflow instead of a collection of isolated snippets.

By the end of this lesson, you'll be able to:

  • Apply Errors vs exceptions in a production-shaped Flutter feature
  • Apply try/catch/finally in a production-shaped Flutter feature
  • Apply Custom exceptions in a production-shaped Flutter feature
  • Apply Stack traces in a production-shaped Flutter feature

Core mental model

Connect each API to the decision it supports. Flutter code stays maintainable when state, ownership, lifecycle, and platform boundaries are explicit.

ConceptWhat it meansDecision rule
ExceptionA non-local interruption for an operation that cannot continue normallyCatch only where context can be added, recovery chosen, or the boundary translated
Stack traceThe execution path associated with a failurePreserve it when wrapping or reporting unexpected failures
Result typeExpected success and failure represented as ordinary dataUse when callers must branch on a known business outcome

Professional workflow

Work in small vertical slices and keep behavior observable from the first iteration.

  1. Define the typed repository failure contract boundary: user goal, inputs, visible states, ownership, and expected failures.
  2. Build the smallest working vertical slice with typed data and explicit dependencies.
  3. Represent loading, empty, success, and failure behavior where the feature can encounter them.
  4. Verify logic away from the UI, then exercise the rendered behavior at its public boundary.
  5. Inspect lifecycle, accessibility, performance, security, and platform behavior before widening the feature.
  6. Refactor only after behavior is protected by repeatable evidence.

Protect the frame

Keep build methods predictable, move side effects to explicit owners, and measure before introducing caches, isolates, or architectural layers.

Guided Flutter lab

Build a focused typed repository failure contract slice

This compact example keeps the important ownership and data-flow decisions visible so the behavior is easy to extend and test.

lib/result.dart
sealed class Result<T> { const Result(); }
class Success<T> extends Result<T> { const Success(this.value); final T value; }
class Failure<T> extends Result<T> { const Failure(this.message); final String message; }

Future<Result<String>> loadTitle(Future<String> Function() request) async {
  try {
    return Success(await request());
  } on FormatException {
    return const Failure('The server returned invalid course data.');
  } on Exception {
    return const Failure('The course is temporarily unavailable.');
  }
}

Production practice

Contract

Define the typed repository failure contract inputs, outputs, owner, lifecycle, visible states, and platform assumptions before selecting APIs or packages.

Verification

Protect pure rules with unit tests and the rendered public contract with widget or integration evidence; include one unavailable or failure case.

Operations

Keep dependencies replaceable, log actionable context without user secrets, and measure user-visible behavior before optimizing.

Common failure mode

Catching every Object and returning an empty value hides programmer errors and erases the difference between no data and a failed operation.

Independent workshop

Extend the guided lab into a review-ready typed repository failure contract feature that fits the running course portfolio app.

Your finished workshop must include:

  • Errors vs exceptions
  • try/catch/finally
  • Custom exceptions
  • Stack traces
  • Sealed result types
  • Automated verification and a short design note

Definition of done

Demonstrate the happy path, an empty or unavailable state, and at least one failure path. Add an automated check and a short note explaining one design decision.

Recap & quick check

Key takeaways

  • Exception: Catch only where context can be added, recovery chosen, or the boundary translated
  • Stack trace: Preserve it when wrapping or reporting unexpected failures
  • Result type: Use when callers must branch on a known business outcome

Quick check

1. Which rule best applies to Exception?

2. Which rule best applies to Stack trace?

3. Which rule best applies to Result type?

Next: Futures & async/await