Question?
In given code find out the output
public int divide(int a, int b )
{
try
{
return a/b;
}
catch(Exception exception)
{
return -10;
}
finally
{
return -100;
}
}
=> invoke above method using statement divide(10,10) what will be the output.
=> output
-100
=> explanation
When execution control comes inside the divide method, then JVM create below stack frames.
one for try block
one for catch block
one for finally block.
In java finally block get executed for every execution of try except System exit or System error.
So you can imagine above code in stack/block at runtime like below.
So you can imagine above code in stack/block at runtime like below.
Divide method metadata
|
I/P => divide(10,10)
execution of above statement as follows.
try block
return 10/10; will result into => return 0 , this result value is set to be return and is stored in method block/metadata.
then method block is waiting for execution completion of finally block
finally block
inside finally block again return metadata is set to -100.
so we have now latest value for return is -100. which need to be return so output is -100;
Interviewer might tweak you with ArithmeticException but output will be remain same as finally block will override the value of the return variable of a catch and try block every time.
execution of above statement as follows.
try block
return 10/10; will result into => return 0 , this result value is set to be return and is stored in method block/metadata.
then method block is waiting for execution completion of finally block
finally block
inside finally block again return metadata is set to -100.
so we have now latest value for return is -100. which need to be return so output is -100;
Interviewer might tweak you with ArithmeticException but output will be remain same as finally block will override the value of the return variable of a catch and try block every time.
Comments
Post a Comment