首页 > 编程语言 > 详细

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

时间:2020-03-19 14:55:59      阅读:46      评论:0      收藏:0      [点我收藏+]

(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

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

原文:https://www.cnblogs.com/dirsoen/p/12524137.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!