CKTIS / Java
finally — cleanup after try
finally — cleanup after try: A finally clause belongs to try and runs after the try block and any selected catch when control completes them normally or by most abrupt-completion reasons.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
finallyA finally clause belongs to try and runs after the try block and any selected catch when control completes them normally or by most abrupt-completion reasons.
Put cleanup in finally only when try-with-resources cannot express it; close AutoCloseable resources primarily with try-with-resources.
A return, throw, break, or continue from finally replaces the earlier result or exception, so finally should not complete abruptly itself.
finally does not run if the JVM terminates through System.exit or halt, crashes, or the thread never leaves the try block.
choose prints try first, then finally before the pending return completes, and main ends with the exact line result=7.
Examples
public class Main {
static int choose() {
try {
System.out.println("try");
return 7;
} finally {
System.out.println("finally");
}
}
public static void main(String[] args) {
System.out.println("result=" + choose());
}
}
Result
try finally result=7
choose prints try first, then finally before the pending return completes, and main ends with the exact line result=7.