3

Consider this question I was asked in an interview

public class Test_finally {
    private static int run(int input) {
        int result = 0;
        try { 
            result = 3 / input;
        } catch (Exception e) {
            System.out.println("UnsupportedOperationException");
            throw new UnsupportedOperationException("first");
        } finally {
            System.out.println("finally input=" + input);
            if (0 == input) {
                System.out.println("ArithmeticException");
                throw new ArithmeticException("second");
            }
        }

        System.out.println("end of method");
        return result * 2;
    }

    public static void main(String[] args) {
        int output = Test_finally.run(0);
        System.out.println("  output=" + output);
    }
}

Output of this program throws ArithmeticException not UnsupportedOperationException

Interviewer simply asked how will i let the client know the original exception raised was of type UnsupportedOperationException not ArithmeticException. I didn't know that

1 Answer 1

1

Never return or throw in a finally block. As an interviewer i would expect that answer.

A crappy interviewer looking for a minor technical detail might expect you know Exception.addSuppressed(). You can not actually read the thrown exception in a finally block so you need to store it in the throw block to reuse it.

So something like that:

private static int run(int input) throws Exception {
    int result = 0;
    Exception thrownException = null;
    try {
        result = 3 / input;
    } catch (Exception e) {
        System.out.println("UnsupportedOperationException");
        thrownException = new UnsupportedOperationException("first");
        throw thrownException;
    } finally {
        try {
            System.out.println("finally input=" + input);
            if (0 == input) {
                System.out.println("ArithmeticException");
                throw new ArithmeticException("second");
            }
        } catch (Exception e) {
            // Depending on what the more important exception is,
            // you could also suppress thrownException and always throw e
            if (thrownException != null){
                thrownException.addSuppressed(e);
            } else {
                throw e;
            }
        }
    }

    System.out.println("end of method");
    return result * 2;
}
Sign up to request clarification or add additional context in comments.

1 Comment

One may not deliberately throw from a finally block, but various things can cause unchecked (and unexpected) exceptions to occur within finally blocks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.