finally
- Dart course
- Beginner
- Lesson 102/116
- 5 min
Learn the cleanup block with finally.
finally
After a try block you can add a finally block. This block always runs, whether or not an error occurred. It is used for cleanup: closing a file, terminating a connection, resetting a flag.
Example: try { open(); process(); } catch (e) { print(e); } finally { close(); }. close() is called both on success and on failure. Even if the error is caught, finally runs before the program continues. You can write code without finally; but adding it is a good habit to avoid leaking resources.
Order: try, catch, finally
The three blocks run in order. First the code inside try runs. If an error occurs catch runs. Finally finally always runs. Even if the error is not caught by catch, finally still runs; then the error propagates up.
A typical pattern: open(), process(), close(). close() belongs in finally so the resource is released even if process() fails. You can put return inside finally but it is not recommended; it overrides a return from try or catch and hurts readability.
Practice Your turn: cleanup with finally
Declare a String variable message set to "open" at the start. Inside try call int.parse on a non-numeric string. Inside catch (e) set message to "error". Inside finally set message to "closed" and print it.
Starter code
void main() {
// message = "open"
// try parsing a non-numeric string
// catch sets message = "error"
// finally sets message = "closed" and prints
}Sample solution
void main() {
var message = "open";
try {
int.parse("apple");
} catch (e) {
message = "error";
} finally {
message = "closed";
print(message);
}
}Expected output
closed
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does the finally block run?
try {
process();
} catch (e) {
print(e);
} finally {
close();
}- Always
- Only on error
- Only on success Correct answer
- Never
Explanation: finally always runs; it is independent of error or success.
2 The finally block
try {
process();
} catch (e) {
print(e);
} ____ {
close();
}
try {
process();
} catch (e) {
print(e);
} finally {
close();
}
Explanation: The finally block does cleanup.
3 Match try/catch/finally
| Term | Meaning |
|---|---|
try |
holds risky code |
catch |
catches the error |
finally |
does cleanup |
close() |
called inside finally |