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
EasyCreate 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.
- Read a string input representing the filename to process
- Read a string input representing the file content
- Read a string input representing whether to simulate an error (
"error"or"success") - Use a
try-catch-finallystructure to simulate file processing: - In the
tryblock: 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
catchblock: Handle any exception that occurs during processing - In the
finallyblock: Always perform cleanup operations regardless of success or failure - 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 successfullyIf 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 errorsIf 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 successfullyYour 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
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List6Basic Error Handling
What are Exceptions?The 'try-catch' BlockCatching Exceptions with 'on'The 'finally' BlockThrowing an ExceptionRecap - Safe Division