Java Programming - Exceptions - Discussion

Discussion Forum : Exceptions - Finding the output (Q.No. 3)
3.
What will be the output of the program?
public class X 
{  
    public static void main(String [] args) 
    {
        try 
        {
            badMethod();  
            System.out.print("A"); 
        }  
        catch (Exception ex) 
        {
            System.out.print("B");  
        } 
        finally 
        {
            System.out.print("C"); 
        } 
        System.out.print("D"); 
    }  
    public static void badMethod() 
    {
        throw new Error(); /* Line 22 */
    } 
}
ABCD
Compilation fails.
C is printed before exiting with an error message.
BC is printed before exiting with an error message.
Answer: Option
Explanation:

Error is thrown but not recognised line(22) because the only catch attempts to catch an Exception and Exception is not a superclass of Error. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java.lang.Error).

Discussion:
29 comments Page 2 of 3.

Murali said:   8 years ago
I have executed the above program.

And I got output only error message and "C" is not printed.

Can anyone explain the flow?

Thank you.

Ram said:   1 decade ago
The answer is B.

Compilation fail because it complain to required Throwable instead of Exception in catch block. TRY IT.

Hritika said:   10 years ago
Isn't is mandatory to use throws keyword with bad method () if throw keyword is used in the method definition. ?

Akhilesh said:   1 decade ago
Answer is C because Error class is not extends exception class it extends Throwable interface.

Suma said:   9 years ago
@Sonika.

Throwable is the parent class, exception and error are subclass of throwable.

Aishwarya said:   7 years ago
D is also printed because after finally{ } block all statements are executed.

Sachith said:   9 years ago
Can anyone explain why this line not execute "System.out. print("D") ;"?

Kleen said:   1 decade ago
if(n&&(n-1)==0)
{
//power of 2
}
else
{
//not a power of 2
}

Sonika said:   9 years ago
Anyone exlain the hierarchy of exception handling for me please.

Steve said:   1 decade ago
Why does System.out.print("D"); not execute?


Post your comments here:

Your comments will be displayed after verification.