Java Programming - Exceptions - Discussion

7. 

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() {} 
} 

[A]. AC
[B]. BC
[C]. ACD
[D]. ABCD

Answer: Option C

Explanation:

There is no exception thrown, so all the code with the exception of the catch statement block is run.


Phanindra said: (Apr 9, 2013)  
If there is no exception in a class, if we put try and catch blocks then statements in catch block are executed or not.

Sandeep said: (Apr 15, 2014)  
How we came to know that there is no exception thrown in try block?

Savitha said: (Jun 3, 2014)  
How we came to know that there is no exception thrown in try block?

Saurabh said: (Jan 16, 2016)  
@Phanindra: If there is no exception in a class, if we put try and catch blocks then statements in catch block are not executed. Catch blocks are executed only when Exception is thrown.

Kamlesh said: (Feb 19, 2016)  
@Kamlesh:

How can I get ACD? If once cursor come out of try block then never return back to the try block, then how can we get ACD?

Execution start from main and then goes to the try block and execute badMethod(); Cursor goes to badMethod(), then how can Cursor next time Print A in try block.

Anji said: (Jun 17, 2016)  
Frist control enter in the try block it called method but method not having written type again control enter into the try block print "A" and if executed control directly enter into the finally block remaing all statment it will print.

Sonika said: (Aug 28, 2016)  
Here we are calling a badMethod(); but it is not declared entire program? so how can "A" be printed?

Kapil said: (Feb 7, 2017)  
If an exception raised in an try block then the catch block will executed.

TheExodu5 said: (Mar 20, 2017)  
e assume badMethod will return an exception due to the name alone, but if we look at the code, badMethod() is simply a void method that does nothing. It will complete successfully. Therefore:

badMethod() completes successfully.
A is printed.
(no exception is thrown so Catch is ignored)
Finally, executes: B is printed.
D is printed.

Raju said: (Nov 22, 2018)  
After finally block nothing will execute, But "D" is printed which is after finally block.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.