Skip to main content
The rethrow statement propagates a currently caught exception out of the enclosing catch clause, preserving the original exception object and its associated stack trace. It functions exclusively within exception handling blocks to transfer control to the nearest enclosing exception handler in the call stack.

Syntax

The rethrow keyword appears as a standalone statement within an on or catch block.
try {
  methodThatThrows();
} catch (e) {
  // Perform intermediate logic
  rethrow; 
}

Operational Semantics

  1. Scope Validity: The statement is syntactically valid only within the scope of an exception handler (catch or on block).
  2. Control Flow: Upon execution, rethrow immediately terminates the current function’s execution and transfers control to the next exception handler up the call stack.
  3. Exception Integrity: Unlike explicitly throwing the caught exception object (e.g., throw e), rethrow maintains the metadata and history of the original exception event.

Stack Trace Preservation

The technical distinction between throw and rethrow centers on StackTrace management.
  • throw e: Initiates a new exception event. The stack trace is reset to the line where throw e is executed, obscuring the original source of the error.
  • rethrow: Resumes the propagation of the original exception. The stack trace retains the complete history starting from the initial point of failure.

Visualization of Stack Trace Behavior

void riskyMethod() {
  throw FormatException('Original Error');
}

void catchAndThrow() {
  try {
    riskyMethod();
  } catch (e) {
    // Resets the stack trace to this call site
    throw e; 
  }
}

void catchAndRethrow() {
  try {
    riskyMethod();
  } catch (e) {
    // Preserves the stack trace pointing to the original throw in riskyMethod
    rethrow;
  }
}
Master Dart with Deep Grasping Methodology!Learn More