Menu
Coddy logo textTech

The 'finally' Block

Part of the Logic & Flow section of Coddy's Dart journey — lesson 41 of 65.

Sometimes you need code that runs no matter what happens in your try-catch block. The finally block serves this exact purpose - it contains code that always executes, whether an exception occurs or not.

The finally block comes after your try and catch blocks. Even if your code runs successfully in the try section, or if an exception is caught and handled, the finally block will still execute.

try {
  // Code that might cause an exception
  int result = 10 ~/ 2;
  print("Result: $result");
} catch (e) {
  print("An error occurred: $e");
} finally {
  print("This always runs!");
}

This makes the finally block perfect for cleanup operations like closing files, releasing resources, or logging that an operation has completed. No matter what happens in your error handling, you can guarantee that certain code will always run.

challenge icon

Challenge

Easy

Create a program that demonstrates the finally block by implementing a file processing simulator that always performs cleanup operations regardless of whether an error occurs during processing.

  1. Read a string input representing the filename to process
  2. Read a string input representing the file content
  3. Read a string input representing whether to simulate an error ("error" or "success")
  4. Use a try-catch-finally structure to simulate file processing:
    • In the try block: Check if the error simulation is "error" and throw an exception with the message "File processing failed" if true, otherwise process the file successfully
    • In the catch block: Handle any exception that occurs during processing
    • In the finally block: Always perform cleanup operations regardless of success or failure
  5. Display the processing results in the exact format shown below

For example, if the inputs are "document.txt", "Hello World", "success", your program should output:

File Processing System
======================
Opening file: document.txt
File content: Hello World
Processing file successfully...
File processed: 11 characters found
Cleanup: Closing file handles
Cleanup: Releasing memory resources
Cleanup: Logging operation completion
Processing completed successfully

If the inputs are "report.pdf", "Annual Report Data", "error", your program should output:

File Processing System
======================
Opening file: report.pdf
File content: Annual Report Data
Error occurred: File processing failed
Unable to complete file processing
Cleanup: Closing file handles
Cleanup: Releasing memory resources
Cleanup: Logging operation completion
Processing completed with errors

If the inputs are "config.json", "{\"setting\": \"value\"}", "success", your program should output:

File Processing System
======================
Opening file: config.json
File content: {"setting": "value"}
Processing file successfully...
File processed: 19 characters found
Cleanup: Closing file handles
Cleanup: Releasing memory resources
Cleanup: Logging operation completion
Processing completed successfully

Your program must use a try-catch-finally structure where the finally block always executes the three cleanup operations in the exact order shown. In the try block, check if the error simulation input equals "error" and throw an exception if true. If no error is simulated, count the characters in the file content using the length property. The finally block should always print the cleanup messages and determine the final completion status based on whether an error occurred.

Cheat sheet

The finally block contains code that always executes after try-catch, regardless of whether an exception occurs or not.

try {
  // Code that might cause an exception
  int result = 10 ~/ 2;
  print("Result: $result");
} catch (e) {
  print("An error occurred: $e");
} finally {
  print("This always runs!");
}

The finally block is perfect for cleanup operations like closing files, releasing resources, or logging completion status.

Try it yourself

import 'dart:io';

void main() {
  // Read input
  String? filename = stdin.readLineSync();
  String? content = stdin.readLineSync();
  String? errorSimulation = stdin.readLineSync();
  
  // Display system header
  print("File Processing System");
  print("======================");
  print("Opening file: $filename");
  print("File content: $content");
  
  // TODO: Write your code below
  // Use try-catch-finally structure to simulate file processing
  // - In try block: check if errorSimulation equals "error" and throw exception if true
  // - In catch block: handle any exception
  // - In finally block: always perform cleanup operations
  
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow