Skip to main content
The try-finally statement guarantees the execution of a specific code block (the finally clause) regardless of whether an exception is thrown or a control flow transfer occurs within the associated try block. It ensures that finalization logic runs unconditionally before the current scope is exited.

Syntax

try {
  // Protected code block
  // May throw an exception or return
} finally {
  // Unconditional code block
  // Always executes
}

Execution Mechanics

The execution flow follows strict precedence rules depending on the outcome of the try block:
  1. Normal Completion: If the try block executes without errors, the finally block executes immediately after the last statement of the try block.
  2. Exception Propagation: If an exception is thrown within the try block and no catch clause is present:
    • Execution of the try block halts immediately.
    • The finally block executes.
    • After the finally block completes, the exception resumes propagation up the call stack.

Interaction with Control Flow

The finally block intercepts control flow statements (return, break, continue, rethrow) initiated within the try block. The finally block executes before the control transfer completes.

Return Statement Example

If a return statement is encountered in the try block, the return value is calculated, but the method exit is paused until the finally block executes.
String demoFlow() {
  try {
    print('1. Try block start');
    return 'Result'; // Execution pauses here
  } finally {
    print('2. Finally block executes');
  }
}
// Output:
// 1. Try block start
// 2. Finally block executes
// Returns: 'Result'

Chained with Catch

When combined with on or catch, the finally block remains the last step in the sequence.
try {
  throw Exception('Critical Failure');
} catch (e) {
  print('Exception handled');
} finally {
  print('Cleanup executed');
}
Execution Order:
  1. Exception thrown in try.
  2. Control transfers to catch.
  3. catch block completes.
  4. finally block executes.
  5. Execution continues after the finally block.
Master Dart with Deep Grasping Methodology!Learn More