January 12, 2014

Tricky Java job interview questions #1 - discarded exceptions

In May last year I have joined Stackoverflow and started following Java questions. After a few months of actively participating in Stackoverflow, answering questions and learning from others' answers I must say that Stackoverflow is a great source of knowledge. Yes, there are a lot of very simple questions, but among them there are also challenges.

During the last few months I have seen numerous very interesting, and tricky, questions, questions that might be used on Java job interviews. Without further ado, let us start with question #1: What will be the result of executing the following code:

try {
    try {
        System.out.print("1");
        throw new Exception("a");
    } catch (Exception e) {
        System.out.print("2");
        throw new Exception("b");
    } finally {
        System.out.print("3");
        throw new Exception("c");
    }
} catch (Exception e) {
    System.out.print(e.getMessage());
}

Answer: 123c

Explanation: When a finally block throws an Exception (Exception("c")) then the exception thrown in the try block (Exception("b")) is discarded
From the Java Language Specification 14.20.2.:
If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice:
  • If the finally block completes normally, then the try statement completes abruptly for reason R.
  • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).


Inspired by this Stackoverflow question.

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete