try, finally, and cleanup

suggest change

A finally block runs when control leaves its try block, whatever the reason: the block finished normally, it threw, or it left early with return, break or continue. That makes finally the place to release things you acquired: close files and sockets, return connections to a pool, delete temporary files, restore state you changed.

This article covers:

The examples were run with Dart 3.13. For throwing and catching exceptions in general see Exceptions and Custom exception.

try, catch and finally

A try statement has a body, zero or more on/catch clauses, and an optional finally clause. It needs at least one catch or a finally:

int parsePort(String s) {
  print('parsing "$s"');
  try {
    final port = int.parse(s);
    print('parsed $port');
    return port;
  } on FormatException catch (e) {
    print('bad input: ${e.message}');
    return 80;
  } finally {
    print('finally for "$s"');
  }
}

void main() {
  print(parsePort('8443'));
  print('---');
  print(parsePort('http'));
}

Output:

parsing "8443"
parsed 8443
finally for "8443"
8443
---
parsing "http"
bad input: Invalid radix-10 number
finally for "http"
80

In both calls the finally block runs after everything else in the try statement and before the function's result reaches the caller:

finally runs on every exit path

finally runs whether the body finishes, throws, returns early, or jumps out of a loop with break or continue:

void step(String label, void Function() body) {
  try {
    body();
    print('$label: body finished');
  } catch (e) {
    print('$label: caught $e');
  } finally {
    print('$label: finally');
  }
}

String early(bool quit) {
  try {
    if (quit) return 'returned early';
    return 'returned at end';
  } finally {
    print('  finally runs before the caller sees the result');
  }
}

void main() {
  step('normal', () {});
  step('throws', () => throw StateError('boom'));
  print(early(true));

  for (var i = 0; i < 4; i++) {
    try {
      if (i == 1) continue;
      if (i == 3) break;
      print('loop body $i');
    } finally {
      print('loop finally $i');
    }
  }
}

Output:

normal: body finished
normal: finally
throws: caught Bad state: boom
throws: finally
  finally runs before the caller sees the result
returned early
loop body 0
loop finally 0
loop finally 1
loop body 2
loop finally 2
loop finally 3

Note iterations 1 and 3: continue and break skip the rest of the body, but not the finally block.

try/finally without catch

You don't need to catch an exception to clean up after it. A try/finally without catch runs the cleanup and then lets the exception continue to the caller:

void load(String name) {
  try {
    print('loading $name');
    throw StateError('cannot open $name');
  } finally {
    print('cleanup after $name');
  }
}

void main() {
  try {
    load('config.json');
    print('not reached');
  } catch (e) {
    print('main caught: $e');
  }
}

Output:

loading config.json
cleanup after config.json
main caught: Bad state: cannot open config.json

This is the most common form in library code. The function that opened a resource is responsible for closing it, but it usually has no idea how to handle the error, so it should let the error propagate to code that does.

catch, rethrow and finally

catch (e, st) gives you the exception and its stack trace. rethrow throws the same exception again with its original stack trace. The finally block still runs, after the catch clause and before the exception leaves the function:

StackTrace? original;

void parseConfig(String text) {
  if (!text.startsWith('{')) throw FormatException('not JSON: $text');
}

void loadConfig(String text) {
  try {
    parseConfig(text);
  } catch (e, st) {
    original = st;
    print('logging: $e');
    rethrow; // keeps the original stack trace
  } finally {
    print('finally after rethrow');
  }
}

void main() {
  try {
    loadConfig('port = 80');
  } on FormatException catch (e, st) {
    print('main: ${e.message}');
    print('same stack trace: ${st.toString() == original.toString()}');
  }
}

Output:

logging: FormatException: not JSON: port = 80
finally after rethrow
main: not JSON: port = 80
same stack trace: true

Use rethrow rather than throw e: throw e starts a new stack trace at the throw, which hides where the error happened. If you need to rethrow an error later, outside its catch block, use Error.throwWithStackTrace(e, st).

Pitfall: return in finally

A return inside finally replaces whatever the try block was doing. If the try block returned a value, that value is discarded. If it threw, the exception is silently swallowed:

int swallow() {
  try {
    throw StateError('important error');
  } finally {
    return -1; // discards the exception
  }
}

int override() {
  try {
    return 1;
  } finally {
    return 2; // replaces the return value
  }
}

void main() {
  print(swallow());
  print(override());
}

Output:

-1
2

swallow() returns -1 and the StateError is gone without a trace. The same applies to break and continue in a finally block that jump out of it. The control_flow_in_finally lint, part of the recommended lint set (package:lints/recommended.yaml), flags this:

info - ex04.dart:5:5 - Use of 'return' in a 'finally' clause. Try restructuring the code. - control_flow_in_finally

Keep finally blocks for cleanup only, and compute results in the try block.

Pitfall: exceptions thrown from cleanup

If the finally block throws while an exception is already propagating, the new exception replaces the original. You get the error from the cleanup code, which is usually much less useful than the one that caused the problem:

class Conn {
  void close() => throw StateError('close failed: socket already reset');
}

void query(Conn c) {
  try {
    throw FormatException('bad SQL near "SELEC"');
  } finally {
    c.close();
  }
}

void queryKeepingOriginal(Conn c) {
  try {
    throw FormatException('bad SQL near "SELEC"');
  } finally {
    try {
      c.close();
    } catch (e) {
      print('  ignoring close error: $e');
    }
  }
}

void main() {
  try {
    query(Conn());
  } catch (e) {
    print('caught: $e');
  }
  try {
    queryKeepingOriginal(Conn());
  } catch (e) {
    print('caught: $e');
  }
}

Output:

caught: Bad state: close failed: socket already reset
  ignoring close error: Bad state: close failed: socket already reset
caught: FormatException: bad SQL near "SELEC"

query reports the close failure, and the FormatException that explains what went wrong is lost. When cleanup can fail and the original error matters more (it nearly always does), catch errors inside the finally block and log them. The using and Cleanup helpers later in this article handle this more carefully.

Pitfall: variables and late in finally

A variable declared inside try isn't visible in finally, because they are separate blocks. Declare it before the try. If acquiring the resource can itself fail, you have two good options:

The second option looks like this:

import 'dart:io';

int countLines(String path) {
  // Declared outside try so finally can see it.
  RandomAccessFile? raf;
  try {
    raf = File(path).openSync();
    final bytes = raf.readSync(raf.lengthSync());
    return bytes.where((b) => b == 10).length;
  } finally {
    // raf is null if openSync itself threw.
    raf?.closeSync();
    print('closed: ${raf != null}');
  }
}

void main() {
  final dir = Directory.systemTemp.createTempSync('finally_demo');
  final file = File('${dir.path}/notes.txt')
    ..writeAsStringSync('one\ntwo\nthree\n');

  print(countLines(file.path));

  try {
    countLines('${dir.path}/missing.txt');
  } on FileSystemException catch (e) {
    print('error: ${e.message}');
  }

  dir.deleteSync(recursive: true);
}

Output:

closed: true
3
closed: false
error: Cannot open file

When the file doesn't exist, openSync throws, raf stays null, and raf?.closeSync() does nothing. The error from openSync then propagates as usual.

Don't use late final for this. It looks tidy, but if the assignment never happens, reading the variable in finally throws a LateInitializationError, which replaces the real error:

import 'dart:io';

void main() {
  late final RandomAccessFile raf;
  try {
    raf = File('does-not-exist.txt').openSync();
    print(raf.lengthSync());
  } finally {
    raf.closeSync(); // raf was never assigned
  }
}

Output:

Unhandled exception:
LateInitializationError: Local 'raf' has not been initialized.

The FileSystemException that explains the problem is gone.

Closing files and sinks

File handles are limited, and on Windows an open file can't be deleted or renamed. Close every RandomAccessFile you open and every IOSink you get from File.openWrite. The openWrite call doesn't throw (errors are reported later, by close() or flush()), so it can go before the try:

import 'dart:io';

Future<void> writeReport(File file, List<String> rows) async {
  final sink = file.openWrite();
  try {
    sink.writeln('id,name');
    for (final (i, row) in rows.indexed) {
      if (row.isEmpty) throw ArgumentError('row $i is empty');
      sink.writeln('$i,$row');
    }
  } finally {
    // close() flushes buffered data and releases the file handle.
    await sink.close();
  }
}

Future<void> main() async {
  final dir = await Directory.systemTemp.createTemp('finally_demo');
  final file = File('${dir.path}/report.csv');

  await writeReport(file, ['ann', 'bob']);
  print(await file.readAsString());

  try {
    await writeReport(file, ['ann', '', 'bob']);
  } on ArgumentError catch (e) {
    print('failed: ${e.message}');
  }
  print(await file.readAsString());

  // Handle is closed, so the directory can be deleted (on Windows too).
  await dir.delete(recursive: true);
  print('deleted: ${!await dir.exists()}');
}

Output:

id,name
0,ann
1,bob

failed: row 1 is empty
id,name
0,ann

deleted: true

IOSink buffers writes, and close() flushes the buffer and releases the handle. Without the finally, the second call would leave the file open after the ArgumentError, the partially written data might never be flushed, and on Windows dir.delete would fail because the file is in use.

When the whole job fits in one call, the convenience methods File.writeAsString, File.readAsString, File.readAsLines and friends open and close the file for you, so there's nothing to clean up. See Bytes and binary data for more about RandomAccessFile.

finally in async functions

Inside an async function, try/catch/finally works across await: an exception thrown by an awaited future is caught by the surrounding catch, and finally runs after the awaited future completes. But this only works if you actually await. A future that isn't awaited runs on its own, and the try statement is long finished by the time it fails:

Future<String> fetch(String url) async {
  await Future.delayed(const Duration(milliseconds: 50));
  throw StateError('connection refused: $url');
}

Future<void> withoutAwait() async {
  try {
    fetch('https://a.example'); // not awaited
    print('try block done');
  } catch (e) {
    print('never caught here: $e');
  } finally {
    print('finally ran before fetch finished');
  }
}

Future<void> withAwait() async {
  try {
    await fetch('https://b.example');
  } catch (e) {
    print('caught: $e');
  } finally {
    print('finally ran after fetch finished');
  }
}

Future<void> main() async {
  await withAwait();
  print('---');
  await withoutAwait();
  await Future.delayed(const Duration(milliseconds: 100));
  print('main done');
}

Output:

caught: Bad state: connection refused: https://b.example
finally ran after fetch finished
---
try block done
finally ran before fetch finished
Unhandled exception:
Bad state: connection refused: https://a.example
#0      fetch (file:///.../bin/ex08.dart:3:3)
<asynchronous suspension>

In withoutAwait, fetch starts and the try block continues immediately. The finally block runs while the request is still in flight, and the failure 50 ms later is not caught by anything, so it crashes the program as an unhandled exception.

The same bug appears when you return a future from inside try without awaiting it. The function returns the pending future, finally closes the connection, and the query, still in flight, finds the connection closed:

class Conn {
  bool open = true;
  Future<String> query(String sql) async {
    await Future.delayed(const Duration(milliseconds: 10));
    if (!open) throw StateError('connection closed');
    return 'rows for $sql';
  }

  void close() {
    open = false;
    print('closed');
  }
}

Future<String> broken(Conn c) async {
  try {
    return c.query('SELECT 1'); // no await
  } finally {
    c.close();
  }
}

Future<String> fixed(Conn c) async {
  try {
    return await c.query('SELECT 1');
  } finally {
    c.close();
  }
}

Future<void> main() async {
  print(await fixed(Conn()));
  try {
    print(await broken(Conn()));
  } catch (e) {
    print('broken: $e');
  }
}

Output:

closed
rows for SELECT 1
closed
broken: Bad state: connection closed

In broken, close() runs before the query has finished, so the query fails with "connection closed". return await keeps the try active until the future completes. The analyzer catches this case:

warning - ex12.dart:17:5 - Returning a 'Future' without 'await' inside a try block. Try adding an 'await'. - unawaited_return_in_try_block

For futures that are not returned, enable the unawaited_futures lint, and wrap futures you really mean to run in the background in unawaited(...) from dart:async. See Async and Await for more.

Future.whenComplete

whenComplete is the finally of the Future API. Its callback runs when the future completes with a value or an error, and the original result passes through unchanged:

Future<int> compute(bool fail) async {
  await Future.delayed(const Duration(milliseconds: 10));
  if (fail) throw StateError('compute failed');
  return 42;
}

void main() {
  var busy = true;

  compute(false)
      .whenComplete(() => busy = false)
      .then((v) => print('value $v, busy=$busy'));

  compute(true)
      .whenComplete(() => print('cleanup runs on error too'))
      .catchError((Object e) {
        print('error: $e');
        return -1;
      });
}

Output:

value 42, busy=false
cleanup runs on error too
error: Bad state: compute failed

If the callback returns a future, whenComplete waits for it before passing the result on. If the callback throws, that error replaces the original result, just like an exception in a finally block. In async functions, prefer try/finally; whenComplete is useful in code that chains futures.

Cleanup in streams and generators

An async* generator can use try/finally to release what it opened. The finally block runs when the generator finishes normally, when it throws, and also when the listener cancels the subscription. await for cancels the subscription when you leave the loop with break, return or an exception, and methods like first cancel it once they have their value:

Stream<String> readLines(String name) async* {
  print('open $name');
  try {
    for (var i = 1; i <= 5; i++) {
      await Future.delayed(const Duration(milliseconds: 5));
      yield '$name line $i';
    }
  } finally {
    print('close $name');
  }
}

Future<void> main() async {
  await for (final line in readLines('a.log')) {
    print(line);
    if (line.endsWith('2')) break; // cancels the subscription
  }

  print('---');
  final first = await readLines('b.log').first;
  print(first);

  print('---');
  try {
    await for (final line in readLines('c.log')) {
      print(line);
      throw FormatException('cannot parse "$line"');
    }
  } on FormatException catch (e) {
    print('caught: ${e.message}');
  }
}

Output:

open a.log
a.log line 1
a.log line 2
close a.log
---
open b.log
close b.log
b.log line 1
---
open c.log
c.log line 1
close c.log
caught: cannot parse "c.log line 1"

Each generator opened its source and closed it again, even though no loop read all five lines. When the subscription is cancelled, the generator is resumed at the yield as if it had executed a return, so its finally blocks run.

Two caveats:

See Sync and async generators and Cancellation and timeouts.

A reusable using helper

Dart has no using statement like C# or try-with-resources like Java, but a generic function gives you the same thing. The resource is passed in, the body gets it as a parameter, and finally closes it:

abstract interface class Closable {
  Future<void> close();
}

class Resource implements Closable {
  final String name;
  Resource(this.name) {
    print('open $name');
  }

  Future<String> read() async => 'data from $name';

  @override
  Future<void> close() async => print('close $name');
}

/// Runs [body] with [resource] and always closes it afterwards.
Future<R> using<T extends Closable, R>(
  T resource,
  Future<R> Function(T) body,
) async {
  try {
    return await body(resource);
  } finally {
    await resource.close();
  }
}

Future<void> main() async {
  final text = await using(Resource('db'), (db) => db.read());
  print(text);

  print('---');
  // Nested: closed in reverse order of opening.
  await using(Resource('input'), (input) async {
    await using(Resource('output'), (output) async {
      print('copy ${await input.read()} to ${output.name}');
    });
  });

  print('---');
  try {
    await using(Resource('cache'), (cache) async {
      throw StateError('cache corrupted');
    });
  } on StateError catch (e) {
    print('caught: ${e.message}');
  }
}

Output:

open db
close db
data from db
---
open input
open output
copy data from input to output
close output
close input
---
open cache
close cache
caught: cache corrupted

return await body(resource) matters here, for the reason shown in the previous section: without the await, the resource would be closed before the body's future completes.

Nesting using calls closes resources in the reverse order they were opened, which is what you want when one resource depends on another. The same pattern appears in package:ffi, whose using function frees native memory allocated in an arena when the callback returns; see dart:ffi.

A defer stack for many resources

Nested try/finally blocks get deeply indented when a function opens many things, and nested using calls aren't much better. An alternative, modelled on Go's defer, is to register a cleanup action right after each successful acquisition and run them all, in reverse order, at the end:

/// Collects cleanup actions and runs them in reverse order, like Go's defer.
class Cleanup {
  final _actions = <(String, Future<void> Function())>[];

  void defer(String label, Future<void> Function() action) =>
      _actions.add((label, action));

  /// Runs every action even if some fail, then reports all failures.
  Future<void> run() async {
    final errors = <Object>[];
    while (_actions.isNotEmpty) {
      final (label, action) = _actions.removeLast();
      try {
        await action();
        print('  cleaned up $label');
      } catch (e) {
        errors.add('$label: $e');
      }
    }
    if (errors.isNotEmpty) throw CleanupException(errors);
  }
}

class CleanupException implements Exception {
  final List<Object> errors;
  CleanupException(this.errors);
  @override
  String toString() => 'CleanupException(${errors.join('; ')})';
}

/// Runs [body]; cleanup errors never hide an error thrown by [body].
Future<R> withCleanup<R>(Future<R> Function(Cleanup) body) async {
  final cleanup = Cleanup();
  final R result;
  try {
    result = await body(cleanup);
  } catch (_) {
    try {
      await cleanup.run();
    } catch (e) {
      print('  (also failed during cleanup: $e)');
    }
    rethrow; // the original error, with its stack trace
  }
  await cleanup.run(); // nothing else failed, so cleanup errors propagate
  return result;
}

Future<void> startServer({required bool failCache, required bool failBind}) =>
    withCleanup((cleanup) async {
      print('open database');
      cleanup.defer('database', () async {});

      print('open cache');
      cleanup.defer('cache', () async {
        if (failCache) throw StateError('cache flush failed');
      });

      print('bind socket');
      if (failBind) throw StateError('port in use');
      cleanup.defer('socket', () async {});
      print('serving');
    });

Future<void> run({required bool failCache, required bool failBind}) async {
  try {
    await startServer(failCache: failCache, failBind: failBind);
  } catch (e) {
    print('error: $e');
  }
  print('---');
}

Future<void> main() async {
  await run(failCache: false, failBind: false);
  await run(failCache: false, failBind: true);
  await run(failCache: true, failBind: true);
  await run(failCache: true, failBind: false);
}

Output:

open database
open cache
bind socket
serving
  cleaned up socket
  cleaned up cache
  cleaned up database
---
open database
open cache
bind socket
  cleaned up cache
  cleaned up database
error: Bad state: port in use
---
open database
open cache
bind socket
  cleaned up database
  (also failed during cleanup: CleanupException(cache: Bad state: cache flush failed))
error: Bad state: port in use
---
open database
open cache
bind socket
serving
  cleaned up socket
  cleaned up database
error: CleanupException(cache: Bad state: cache flush failed)
---

The four runs show the rules:

  1. Everything works: all three resources are cleaned up, newest first.
  2. Binding the socket fails: only the resources that were actually opened are cleaned up, because the socket's cleanup was never registered. The original error reaches the caller.
  3. Binding fails and the cache cleanup fails: the cleanup error is logged, but the caller still sees the error that caused the failure.
  4. Only the cleanup fails: there is no other error to report, so the CleanupException propagates.

Cleanup.run keeps going after a failed action, so one broken cleanup doesn't leak everything registered before it. Shutdown hooks in long-running servers work the same way; see Signals and graceful shutdown.

Restoring state

Cleanup isn't only about releasing resources. Whenever code temporarily changes some state (an indentation level, a "busy" flag, a global setting, terminal echo mode), restore it in a finally block, or one exception leaves the state wrong for the rest of the program:

class Logger {
  int _depth = 0;

  void log(String msg) => print('${'  ' * _depth}$msg');

  /// Indents everything logged by [body], even if it throws.
  T section<T>(String title, T Function() body) {
    log(title);
    _depth++;
    try {
      return body();
    } finally {
      _depth--;
      log('end $title');
    }
  }
}

void main() {
  final log = Logger();
  log.section('build', () {
    log.log('compile');
    try {
      log.section('test', () {
        log.log('run 12 tests');
        throw StateError('1 test failed');
      });
    } on StateError catch (e) {
      log.log('error: ${e.message}');
    }
    log.log('package');
  });
}

Output:

build
  compile
  test
    run 12 tests
  end test
  error: 1 test failed
  package
end build

The nested test section throws, but its finally block still decreases the depth, so error: 1 test failed and package are indented correctly. Without the finally, every line after the exception would be indented one level too deep.

What finally doesn't cover

exit() skips finally

exit() from dart:io stops the VM immediately. It doesn't unwind the stack, so no finally block runs and pending futures are abandoned:

import 'dart:io';

void main() {
  final lock = File('${Directory.systemTemp.path}/finally_exit.lock');
  if (lock.existsSync()) {
    print('stale lock left by pid ${lock.readAsStringSync()}');
  }
  lock.writeAsStringSync('$pid');
  try {
    print('working as pid $pid');
    exit(1); // terminates the VM right here
  } finally {
    lock.deleteSync();
    print('lock removed'); // never printed
  }
}

Output of two consecutive runs:

working as pid 15852
stale lock left by pid 15852
working as pid 24344

The first run's finally never ran, so its lock file is still there. Instead of calling exit() deep inside your code, throw an exception or return a status to main, and let main set exitCode and return normally. Then all finally blocks run on the way out. The same applies to Isolate.kill with Isolate.immediate priority and to the process being killed by the operating system.

Finalizers are not a replacement

Finalizer and NativeFinalizer from dart:core and dart:ffi can call a function after an object has been garbage collected. They are a safety net for resources someone forgot to release, not a cleanup mechanism: the garbage collector decides when (and whether) they run, and nothing runs them when the program exits. Release scarce resources like file handles, sockets and database connections explicitly with try/finally, a close() or dispose() method, or a helper like using. See Memory and garbage collection.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents