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 1 of 3.

Muthu kumar said:   1 decade ago
How it will runs without catch ?

Jafar said:   1 decade ago
How the code works?

Jyoti said:   1 decade ago
Thanx for this info..

Praveen.vaka said:   1 decade ago
Try can exist with out any catch.

Praveen.v said:   1 decade ago
A try can exist with out any catch block but catch can not exit with out try block.

Sonu raj said:   1 decade ago
If method type is void then how it is returning ?

Sai Kumar said:   1 decade ago
return; means it's returning nothing.
So we can just give return;

R.VINOD KUMAR said:   1 decade ago
Finally block is executing means releasing the resources used.

So always resources must be released after using, So Finally block must be executed compulsorly everytime.

If exception raises in try block, then JVM searches for Particular catch block, if catch block is absent then Finally will be executed to close the resources and then error/exception message will be printed on command prompt.

But here in this case no exception raised in try block. So, everything is fine (means simply Finally executed).

Av.nikhil said:   1 decade ago
The "return;" statement in try block has to send the control back to the calling method (main) without returning any value (because it allowed only in void methods). So without searching for catch blocks control going to the calling method.

But anyhow finally block should execute before the control goes the main method.

Akhilesh said:   1 decade ago
If we use finally block it always executes anyhow to complete unfinished tasks. So here Finally will be printed on the output screen as a result.


Post your comments here:

Your comments will be displayed after verification.