Dart try-catch-finally

Summary: in this tutorial, you’ll learn how to use the Dart try-catch-finally statement to handle exceptions and clean up the resource whether the exceptions occur or not.

Introduction to the try-catch-finally statement

The finally is an optional block of the try-catch statement. The finally block always executes whether an exception occurs or not.

In practice, you often use the finally block to clean up the resources. For example, you can close a file or a connection to the database in the finally clause.

The following shows the syntax of the try-catch-finally statement:

try {
    // place the code that may cause exceptions
} catch(e) {
   // place the code that handles the exception
} finally {
   // place the code that clean up the resource
}Code language: Dart (dart)

In this syntax, if an exception occurs the program jumps to the catch block and continues the finally block.

If no exception occurs, the program run until the end of the try block and continues the finally block.

In other words, the finally block always executes whether an exception occurs or not.

Dart try-catch-finally example

The following example uses the try-catch-finally statement to write a text string into a file:

import 'dart:io';

void main() {
  File file;
  IOSink? writer;
  try {
    file = new File('message.txt');
    writer = file.openWrite();
    writer.write('Hello');
  } on FileSystemException {
    print('File not found');
  } finally {
    writer?.close();
  }
}Code language: Dart (dart)

How it works.

First, import the dart:io library so that we can use the file-related objects:

import 'dart:io';Code language: Dart (dart)

Second, place the code that writes the Hello message to a file.

Third, display the error in the on block if an exception occurs.

Finally, close the writer in the finally block whether an exception occurs or not.

Summary

  • Use the finally block if you want to execute a block of code whether an exception occurs or not.
Was this tutorial helpful ?