Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I have a small theoretical problem with try-catch constructions.

I took a practical exam yesterday about Java and I don't understand following example:

try {

    try {

        System.out.print("A");

        throw new Exception("1");

    } catch (Exception e) {

        System.out.print("B");

        throw new Exception("2");

    } finally {

        System.out.print("C");

        throw new Exception("3");

    }

} catch (Exception e) {

    System.out.print(e.getMessage());

}

The question was "what the output will look like?"

I was pretty sure it would be AB2C3, BUT suprise suprise, it's not true.

The right answer is ABC3 (tested and really it's like that).

My question is, where did the Exception("2") go?

1 Answer

0 votes
by (46k points)

Since throw new Exception("2"); is thrown from catch block and not try, it won't be caught again.

See 14.20.2. Execution of try-finally and try-catch-finally.

This is what happening:

try {

    try {

        System.out.print("A"); //Prints A

        throw new Exception("1");   

    } catch (Exception e) { 

        System.out.print("B"); //Caught from inner try, prints B

        throw new Exception("2");   

    } finally {

        System.out.print("C"); //Prints C (finally is always executed)

        throw new Exception("3");  

    }

} catch (Exception e) {

    System.out.print(e.getMessage()); //Prints 3 since see (very detailed) link

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...