Java Programming - Exceptions - Discussion

Discussion Forum : Exceptions - Finding the output (Q.No. 1)
1.
What will be the output of the program?
public class Foo 
{  
    public static void main(String[] args) 
    {
        try 
        { 
            return; 
        } 
        finally 
        {
            System.out.println( "Finally" ); 
        } 
    } 
}
Finally
Compilation fails.
The code runs with no output.
An exception is thrown at runtime.
Answer: Option
Explanation:
If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances:
  1. An exception arising in the finally block itself.
  2. The death of the thread.
  3. The use of System.exit()
  4. Turning off the power to the CPU.

I suppose the last three could be classified as VM shutdown.

Discussion:
25 comments Page 3 of 3.

Bhanu said:   7 years ago
Hi Parul,

Exchanging the place or syntax of the main method will not be affected for execution of program except void must be before main.

ImdaduL Haque said:   7 years ago
I can't understand it. How can it work?

P.vyshnavi said:   7 years ago
I think compilation fails because every try block having catch block is there but in this program, catch block is not there.

Correct me, if I am wrong.
(1)

Suraj Dhaigude said:   5 years ago
In the try block, no any exception so no need to catch block control direct finally method so it's print finally.
(1)

Suraj Dhaigude said:   5 years ago
Thanks all for giving the explanation.


Post your comments here:

Your comments will be displayed after verification.