Things will get interesting if you try to do something in the finally block requiring additional memory:
public class Finally {
public void abc() {
try {
throw new OutOfMemoryError();
} finally {
byte[] b = new byte[1024*1024*1024];
System.out.println("finally");
}
}
public static void main(String[] args) {
new Finally().abc();
}
}
Now when you execute the code (java -Xmx20m Finally
for example), you can easily end up in a situation where your available heap has been exhausted to the extent where the finally
block cannot fully complete, thus its execution cannot be guaranteed. So I would not recommend to rely on finally blocks in case of OutOfMemoryErrors
.