"Nothing in life is to be feared, it is only to be understood."
- Marie Curie
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" );
}
}
}
[A].
Finally
[B].
Compilation fails.
[C].
The code runs with no output.
[D].
An exception is thrown at runtime.
Answer: Option E
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:
An exception arising in the finally block itself.
The death of the thread.
The use of System.exit()
Turning off the power to the CPU.
I suppose the last three could be classified as VM shutdown.
Praveen.Vaka said:
(Mon, Nov 28, 2011 11:19:36 PM)
Try can exist with out any catch.
Praveen.V said:
(Mon, Nov 28, 2011 11:48:28 PM)
A try can exist with out any catch block but catch can not exit with out try block.
Sonu Raj said:
(Fri, Jun 22, 2012 01:07:41 AM)
If method type is void then how it is returning ?
Sai Kumar said:
(Fri, Sep 7, 2012 04:12:00 PM)
return; means it's returning nothing.
So we can just give return;
R.Vinod Kumar said:
(Wed, Oct 17, 2012 10:25:01 AM)
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:
(Wed, May 8, 2013 10:54:53 PM)
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.