Tuesday, 27 March 2018

Return statement in try catch block.


package com.test.yuvagen.basic;

/* Return in try catch block
 * We can have return statement in try catch block but finally block               *will be executed
 * Read more:http://javainterviewprograms.blogspot.in/
 * */

public class ReturnInTryCatch {

          public int returnSomething(int number) {
                   int num = 0;
                   try {
                             num = number / 0;
                             return num;
                   } catch (Exception e) {
                             e.printStackTrace();
                             return num;
                   } finally {
                             System.out.println("I am in finally");
                   }

          }

          public static void main(String args[]) {
                   ReturnInTryCatch ritc = new ReturnInTryCatch();
                   System.out.println(ritc.returnSomething(10));
          }
}

Output:
java.lang.ArithmeticException: / by zero
I am in finally
0
at com.test.yuvagen.basic.ReturnInTryCatch.returnSomething(ReturnInTryCatch.java:8)                                                                                                                 at com.test.yuvagen.basic.ReturnInTryCatch.main(ReturnInTryCatch.java:23)

No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...