Please explain why Exception comes in first program but not in second program.
1) without return statement in read method
class Example
{
public static void read()
{
try
{
int i = 9/0;
}
finally
{
System.out.println("This proogram is giving exception");
}
}
public static void main(String[] fel)
{
read();
}
}
2)with return statement in read method
class Example
{
public static void read()
{
try
{
int i = 9/0;
}
finally
{
System.out.println("This proogram is not giving exception");
return;
}
}
public static void main(String[] fel)
{
read();
}
}
In both instance, the code with throw a
java.lang.ArithmeticException
, however thereturn
in thefinally
discards the exception and instead the method exits without forwarding the exception to the caller.This is one of the reason why in general you should not use a
return
in afinally
-block.This is described in the Java Language Specification (8), 14.20.2 Execution of
try-finally
andtry-catch-finally
:You can find the definition of abrupt and normal completion in JLS 14.1 Normal and Abrupt Completion of Statements. But basically a
return
is considered an abrupt completion.Branching statements(return ,goto ) should no be used inside finally because execution of such statement nullifies other instructions which are executed before finally.
The Java Language Specification says : If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice:
Note - A return statement inside a finally block will cause any exception that might be thrown in the try or catch block to be discarded.
The reason is given in the Java Language Specification rules governing the execution of try/finally blocks. Essentially
An explicit
return
is considered abrupt rather than normal completion, so in your example 2 the return inside the finally masks the divide-by-zero exception raised by the try.