The key points are these:
- In a
try-(catch)-finally
block, thefinally
for that particulartry
block is performed last - You can nest
try
blocks within another, and each of those nestedtry
blocks can have their ownfinally
, which would be performed last for those individualtry
blocks
So yes, finally
is performed last, but only for the try
block it’s attached to.
So given the following snippet:
try {
try {
throw null;
} finally {
System.out.println("Finally (inner)");
}
} catch (Throwable e) {
System.out.println("Catch (outer)");
}
This prints (as seen on ideone.com):
Finally (inner)
Catch (outer)
Observe that:
- Within
(inner)
,Finally
is last (whether or not anycatch
was successful) Catch (outer)
followsFinally (inner)
, but that’s becauseFinally (inner)
is nested inside anothertry
block within(outer)
Similarly, the following snippet:
try {
try {
throw null;
} catch (Throwable e) {
System.out.println("Catch (inner)");
} finally {
System.out.println("Finally (inner)");
throw null;
}
} catch (Throwable e) {
System.out.println("Catch (outer)");
}
This prints (as seen on ideone.com):
Catch (inner)
Finally (inner)
Catch (outer)