­

Java finally return - Exception handling in java

10:49:00

Already we  discussed about finally block in my previous tutorial. This post is to learn finally block behavior when a return statement is encountered inside try, catch or finally block.

Consider below example – What do you think?? Will finally would execute even if there is a return failure statement.
try {
    //try block
    ...
    return success;
}
catch (Exception ex) {
    //catch block
    .....
    return failure;
}
finally {
    System.out.println("Inside finally");
}
The answer is yes. finally block will execute every time. The only case when it doesn’t execute is when it encounters System.exit().

Finally: Example with return statement

class FinallyDemo
{
   public static int myMethod()
   {
       try {
            //try block
            return 0;
       }
       finally {
            //finally
            System.out.println("Inside Finally block");
       }
  }
  public static void main(String args[])
  {
       System.out.println(FinallyDemo.myMethod());
  }
}
Output:
Inside Finally block
0

Does finally block Overrides the values returned by try-catch block?

Yes. Finally clause overrides the value returned by try and catch blocks. Consider below example –
public static int myTestingFuncn(){
  try{
     ....
     return 5;
  } finally {
     ....
     return 19;
   }
}
The above code would return value 19 since the value returned by try has been overridden by finally.


You Might Also Like

0 comments

Thanks for intrest.. We will touch withbyou soon..

Popular Posts

Like us on Facebook