public class ReturnValueFromTryCatchFinally
{
public static void main(String[] args)
{
System.out.println(methodReturningValue());
}
static String methodReturningValue()
{
String s = null;
try
{
s = "return value from try block";
return s;
}
catch (Exception e)
{
s = s + "return value from catch block";
return s;
}
finally
{
s = s + "return value from finally block";
// return s;
}
}
}
If we run this program then we are getting output as "return value from try block". If we remove the comment from the finally
block (return s;
) then we are getting output "return value from try block return value from finally block".
Why isn't it giving the output "return value from try block" and "return value from try block return value from finally block"? Because first it will return from the try
block then it goes to finally
.