Search code examples
javaexceptiontry-catch-finally

Java 'finally' exception throwing rules


Lets say I have a class that has two OutputStream members:

public class A {
    OutputStream os1 = ...
    OutputStream os2 = ...

    ...
}

Now, in this class, I have a cleanup() method which must at least attempt to close both streams:

public void cleanup() throws IOException {
    try {
        os1.close();
    } finally {
        os2.close();
    }
}

Now, I'm confident that the above code will try to close both streams, but what is interesting is what happens when both calls to close() throw an IOException. I want to say that the exception from os2 will propogate upward, but perhaps the behavior is undefined. I've done some googling but I'm not finding anything that answers this question well.


Solution

  • The JLS §14.20.2 describes the behaviour. The exception, that is thrown by the method is the exception caused by os2.close().