Skip to main content
The rethrow statement in Dart is a control flow keyword used exclusively within a catch block to propagate a caught exception up the call stack while preserving its original stack trace. When an exception is caught, the Dart runtime captures both the exception object and the stack trace originating from the initial throw point. If an exception is re-raised using throw e; (where e is the caught exception), the runtime resets the stack trace to the location of that new throw statement. The rethrow keyword circumvents this reset, ensuring that the upstream error handler receives the exact execution context of the original failure.
try {
  // Code that generates an exception
  throw FormatException('Invalid input');
} catch (e, stackTrace) {
  // Local inspection or side-effects occur here
  
  rethrow; // Propagates the original exception and stackTrace
}

Technical Characteristics

  • Lexical Scope Restriction: The rethrow keyword is syntactically invalid and will result in a compile-time error if invoked outside the lexical scope of a catch clause.
  • Stack Trace Integrity: It guarantees that the StackTrace object associated with the exception remains unmodified during propagation.
  • Unconditional Termination: Execution of the current block terminates immediately at the rethrow statement. Control flow is unconditionally transferred to the nearest dynamically enclosing try-catch block.
  • Type Preservation: The runtime type of the exception remains identical to the originally thrown object, allowing upstream on clauses to match the specific exception type accurately.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More