Java Programming - Exceptions - Discussion

Discussion Forum : Exceptions - Finding the output (Q.No. 6)
6.
What will be the output of the program?
public class Test 
{  
    public static void aMethod() throws Exception 
    {
        try /* Line 5 */
        {
            throw new Exception(); /* Line 7 */
        } 
        finally /* Line 9 */
        {
            System.out.print("finally "); /* Line 11 */
        } 
    } 
    public static void main(String args[]) 
    {
        try 
        {
            aMethod();  
        } 
        catch (Exception e) /* Line 20 */
        {
            System.out.print("exception "); 
        } 
        System.out.print("finished"); /* Line 24 */
    } 
}
finally
exception finished
finally exception finished
Compilation fails
Answer: Option
Explanation:

This is what happens:

(1) The execution of the try block (line 5) completes abruptly because of the throw statement (line 7).

(2) The exception cannot be assigned to the parameter of any catch clause of the try statement therefore the finally block is executed (line 9) and "finally" is output (line 11).

(3) The finally block completes normally, and then the try statement completes abruptly because of the throw statement (line 7).

(4) The exception is propagated up the call stack and is caught by the catch in the main method (line 20). This prints "exception".

(5) Lastly program execution continues, because the exception has been caught, and "finished" is output (line 24).

Discussion:
18 comments Page 2 of 2.

Amit said:   10 years ago
Output will be only "finally exception" even though excp is catched program not continue.

Jim Bob said:   1 decade ago
I actually put this in netbeans and ran it under jdk 1.7 and got "exception finished".

Rekha said:   1 decade ago
Please explain meaning of the statement "throw new Exception()" ?

Sankyrahul said:   1 decade ago
Execution of finally must be followed by execution all catch block. ?

Shyam said:   1 decade ago
amethod() is valid or not because some program it shows the error.

Manish said:   1 decade ago
When you throw exception the main function should also have throw.

Bhushan said:   2 decades ago
But every try block must followecd by catch block. ?

Sun said:   8 years ago
Thanks. @Richard.


Post your comments here:

Your comments will be displayed after verification.