Question

Consider below code,

public class Test {

    public void abc() {
        try {
            throw new OutOfMemoryError();
        } finally {
            System.out.println("finally");
        }
    }

    public static void main(String[] args) {
        new Test().abc();
    }

}

Output :

Exception in thread "main" finally
java.lang.OutOfMemoryError
    at Test.abc(Test.java:5)
    at Test.main(Test.java:12)

So, finally block is getting executed in the case, however above output is not fixed each time.

  1. So the question is, Here we are throwing OutOfMemoryError and finally block is getting executed. Is this true for every case ?

  2. If yes then finally block will be executed when OutOfMemoryError will be thrown in reality, means memory area expansion will be performed while execution and enough memory not available ?

Was it helpful?

Solution

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.

OTHER TIPS

that's right like said Sotirios Delimanolis

and more surprisingly even if you put a return in your try block the finally will be executed

From the doc :

"finaly block allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated"

check this for more information http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top