What is the output of the following code?
public class Main { int tryAgain() { int a = 10; try { ++a; } finally { a++; } return a; } public static void main(String args[]) { System.out.println(new Main().tryAgain()); } }
C
The try block executes, incrementing the value of variable a to 11.
This step is followed by execution of the finally block, which also increments the value of variable a by 1, to 12.
The method tryAgain returns the value 12, which is printed by the method main.
public class Main { int tryAgain() { int a = 10; try { /* ww w . jav a2s .c o m*/ ++a; } finally { a++; } return a; } public static void main(String args[]) { System.out.println(new Main().tryAgain()); } }
There are no compilation issues with the code. A try block can be followed by a finally block, without any catch blocks.
Even though the try block doesn't throw any exceptions, it compiles successfully.
The code above generates the following result.