java异常,try...catch...finally代码执行情况,以及代码最终返回值详解

(1)finally块中的代码是无论try中是否发生异常,也无论catch是否可以捕获异常,也不管try和catch中是否有return语句,都会执行的部分
(2)如果finally中有return语句,那么try...catch...finally结构 一定从finally中的return回去
(3)如果finally中没有return语句,那么try...catch...finally结构才会从try或catch中的return回去,但是finally值中代码不会影响最终的返回值

public static void main(String[] args) {
  int test = test(3,5);
  System.out.println(test);
}

public static int test(int x, int y){
  int result = x;
  try{
    if(x<0 || y<0){
    return 0;
  }
  result = x + y;
  return result;
  }finally{
    result = x - y;
  }
}

返回值:8

 

static int i = 0;

public static int test(){
  try{
    return ++i;
  }finally{
    return ++i;
  }
}
返回值:2

posted @ 2020-03-19 14:26  dirsoen  阅读(339)  评论(0)    收藏  举报