Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A catch clause in Dart is an exception-handling construct used immediately following a try block to intercept and process objects thrown during execution. It prevents unhandled exceptions from terminating the current isolate and provides access to the thrown object and its execution context. In Dart, because any non-null object can be thrown, the catch clause is designed to handle arbitrary types, though it is most commonly used with instances of Exception or Error.

Syntax and Parameters

The catch clause accepts one or two parameters:
  1. Exception Object (e): The first parameter captures the thrown object. By default, its type is Object.
  2. Stack Trace (s): The optional second parameter captures an instance of StackTrace, representing the call stack at the exact point the exception was thrown.
try {
  // Executable code that may throw an object
} catch (e, s) {
  // e: The thrown object
  // s: The StackTrace
}

Type-Specific Interception (on keyword)

To handle different exceptions polymorphically, Dart pairs the catch clause with the on keyword. The on keyword filters exceptions based on their runtime type.
  • If you need to inspect the exception object, use on Type catch (e).
  • If you only need to handle the type but do not need the object itself, omit the catch clause entirely and use on Type.
try {
  // Executable code
} on FormatException catch (e, s) {
  // Intercepts only FormatException (and its subtypes)
  // Captures both the exception object and the stack trace
} on StateError {
  // Intercepts StateError (built-in from dart:core)
  // Discards the exception object and stack trace
} catch (e) {
  // Fallback: Intercepts any remaining thrown object
  // Captures only the exception object
}

Evaluation Mechanics

  • Sequential Evaluation: Multiple on/catch blocks are evaluated sequentially from top to bottom. The Dart runtime executes the first block where the thrown object’s runtime type is a subtype of the type specified in the on clause.
  • Catch-All Behavior: A standalone catch block (without an on modifier) acts as a catch-all. It is equivalent to on Object catch (e). It must always be placed at the bottom of the handler chain to prevent unreachable code errors.
  • Propagation via rethrow: Within a catch block, the rethrow keyword can be used to propagate the intercepted exception up the call stack. Unlike throwing a new exception or explicitly throwing the captured object (throw e;), rethrow preserves the original StackTrace of the exception.
try {
  // Executable code
} catch (e, s) {
  // Partial handling logic
  rethrow; // Propagates 'e' while maintaining the original 's'
}
Master Dart with Deep Grasping Methodology!Learn More