Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 61 ยท Errors and Libraries

Exceptions and Error Handling

Learn Dart error handling: throw, try/catch/on/finally, Exception versus Error, rethrow, stack traces and how to design your own custom exception classes.

Programs fail in two broad ways. Sometimes the world misbehaves: a file is missing, a network drops, a user types abc where a number belongs. Other times the program itself is wrong: you index past the end of a list or call a method on a value that should never have been null. Dart handles both with exceptions, objects that are thrown and travel up the call stack until some code catches them.

This lesson shows how to throw, catch, clean up and design your own exceptions, and explains the one distinction every Dart programmer must know: Exception versus Error. The Dart code is read-only, and TypeScript stand-ins run the same ideas.

Throwing

You raise an exception with throw. Dart lets you throw any object, but you should throw instances of Exception or Error:

DART
double divide(int a, int b) {
  if (b == 0) {
    throw ArgumentError('b must not be zero');
  }
  return a / b;
}

int parsePositive(String text) {
  final n = int.tryParse(text);
  if (n == null || n < 0) {
    throw FormatException('Expected a non-negative integer', text);
  }
  return n;
}

throw is an expression, so it can appear in places like final value = map[key] ?? (throw StateError('missing $key'));. When an exception is not caught anywhere, the program (or the current isolate) terminates and prints the exception with a stack trace.

try, catch, on and finally

Wrap risky code in try, then handle specific problems with on clauses:

DART
void main() {
  try {
    print(parsePositive('42'));
    print(parsePositive('abc'));
    print('not reached');
  } on FormatException catch (e) {
    print('Bad input: ${e.message}');
  } on ArgumentError {
    print('Bad argument');
  } catch (e, stackTrace) {
    print('Something unexpected: $e');
    print(stackTrace);
  } finally {
    print('Always runs');
  }
}
TEXT
42
Bad input: Expected a non-negative integer
Always runs

Read the clauses from top to bottom; the first match wins:

  • on Type catches only exceptions of that type (and its subtypes). Add catch (e) to name the object and catch (e, st) to also get the StackTrace.
  • A bare catch (e) catches everything. Put it last, and use it sparingly.
  • finally runs after the try (and any matching catch) whether or not something was thrown, even when you return from inside. It is the place for cleanup such as closing a file.

Order matters: a general on Exception placed before on FormatException would swallow it, and the analyzer warns about dead clauses.

flowchart TD
    T["try block runs"] -->|"no exception"| F["finally block"]
    T -->|"exception thrown"| M{"First matching<br/>on / catch clause"}
    M -->|"found"| C["Handler runs"]
    M -->|"none"| U["Propagates to caller<br/>(after finally)"]
    C --> F

A thrown exception looks for the first matching clause; finally runs on every path.

TypeScript try, catch and finally (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Exception versus Error

Dart splits throwables into two families with different intent.

An Exception describes a problem that a correct program should expect and handle: FormatException (bad text), IOException and its subtypes (files, sockets), TimeoutException. Catching these is normal.

An Error describes a programming mistake: ArgumentError, RangeError, StateError, TypeError, UnsupportedError, NoSuchMethodError, AssertionError. They signal a bug that should be fixed, not handled at runtime. Catching Error to continue running usually hides a bug. The rule of thumb:

  • If a caller can reasonably do something about it (retry, ask the user, fall back), throw an Exception.
  • If it means a caller broke the contract (passed an invalid argument, called methods in the wrong order), throw an Error such as ArgumentError or StateError.

Because catch (e) catches both, prefer on Exception catch (e) when you intend to handle expected failures and let genuine bugs crash loudly during development. In production, a top-level handler (for example Flutter's error hook or a runZonedGuarded wrapper) should log them.

Note that int.parse('abc') throws a FormatException, while int.tryParse('abc') returns null. When failure is a normal outcome, prefer the form that returns null or a result value, and save exceptions for truly exceptional situations.

rethrow and stack traces

Sometimes you want to log or clean up and still let the caller deal with the problem. Use rethrow inside a catch block; it preserves the original stack trace:

DART
Future<void> loadConfig() async {
  try {
    await readFile('config.json');
  } on FormatException catch (e) {
    print('Config is malformed: ${e.message}');
    rethrow;                        // same exception, same stack trace
  }
}

Writing throw e; instead would start a new stack trace at the throw line and hide where the problem began. If you want to convert one exception into another while keeping the history, use Error.throwWithStackTrace(newError, stackTrace) with the trace you captured in catch (e, stackTrace).

Custom exceptions

For failures that belong to your domain, define a class that implements Exception:

DART
class InsufficientFundsException implements Exception {
  InsufficientFundsException({required this.needed, required this.available});

  final double needed;
  final double available;

  @override
  String toString() =>
      'InsufficientFundsException: need $needed but only $available available';
}

void withdraw(double balance, double amount) {
  if (amount > balance) {
    throw InsufficientFundsException(needed: amount, available: balance);
  }
}

Three habits make custom exceptions pleasant to use. Carry structured data in fields so callers can react without parsing text. Override toString so uncaught errors read well. And build small hierarchies, for example an abstract AppException with subclasses NetworkException and ValidationException, so a caller can catch the whole family or one member. Sealed classes work especially well here, since an exhaustive switch can then handle every case (see Class Modifiers: sealed, final, base).

TypeScript A custom exception with data (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Practical advice

  • Catch narrowly. on FormatException tells readers what can go wrong; a naked catch hides mistakes.
  • Do not use exceptions for ordinary control flow, such as ending a loop. They are slower than a plain if and harder to read.
  • Clean up in finally (or with try/finally around closing a resource), not at the end of the try block, which is skipped on error.
  • Never swallow an exception silently (catch (_) {}). At minimum, log it.
  • Asynchronous errors behave the same way inside async functions with await, but a Future that fails without a listener reports an unhandled error. Futures and error handling are covered in the Asynchronous Dart chapter.
  • Validate at boundaries (user input, files, network) and let the rest of the code assume good data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does finally do?

    finally always runs, even if the try block returns or an exception propagates, which makes it the right place for cleanup.
  2. 2. Which type of throwable should signal a bug such as passing an invalid argument?

    Errors represent programming mistakes that should be fixed, while Exceptions represent expected, recoverable problems.
  3. 3. Why use rethrow instead of throw e; inside a catch block?

    rethrow passes the same exception on with its original stack trace, while throw e starts a new trace at the throw line.
  4. 4. In what order are catch clauses checked?

    Dart tests the clauses in order and runs only the first that matches, so put specific on clauses before general ones.
  5. 5. What is the best way to make a custom exception useful to callers?

    A class that implements Exception can carry structured fields, print clearly and be caught by type.

Summary

  • throw raises any object; use Exception types for expected failures and Error types for programming mistakes.
  • try with on Type, catch (e, st) and finally handles errors; the first matching clause wins and finally always runs.
  • Use rethrow to keep the original stack trace, and Error.throwWithStackTrace to convert errors without losing it.
  • Define custom exceptions that implement Exception, carry data and print well.
  • Catch narrowly, never swallow errors silently, and prefer tryParse-style APIs when failure is common.

Next, find problems earlier with Assertions and Debugging.