1. 不带return的执行顺序
异常处理中,try、catch、finally的执行顺序:
如果try中没有异常,执行顺序为:try->finally
如果try中有异常,执行顺序为:try->catch->finally
public class Test {
public static int rank;
public static void main(String[] args) {
rank = 1;
solve2();
System.out.println("over");
}
public static void solve1() throws Exception {
try {
System.out.println("solve 1 try, rank: " + rank++);
throw new Exception("throw by solve 1");
} finally {
System.out.println("solve 1 finally, rank: " + rank++);
}
}
public static void solve2() {
try {
System.out.println("solve 2 try, rank: " + rank++);
solve1();
} catch (Exception e) {
System.out.println("catch exception: " + e.getMessage() + ", rank: " + rank++);
} finally {
System.out.println("solve 2 finally, rank: " + rank++);
}
}
}
// solve 2 try, rank: 1
// solve 1 try, rank: 2
// solve 1 finally, rank: 3
// catch exception: throw by solve 1, rank: 4
// solve 2 finally, rank: 5
// over首先是try执行,如果发生异常,那就直接捕获异常,最后执行finally。但是,如果抛出异常,例如在solve1方法中,throw了一个异常,那么不会立刻回溯到上一方法,而是仍然执行finally。
2. 带return的执行顺序
2.1 try中带return的
基本类型:
public class Test {
public static void main(String[] args) {
System.out.println(testReturn());
}
public static int testReturn() {
int i = 1;
try {
i++;
System.out.println("try: " + i);
return i;
} catch (Exception e) {
i++;
System.out.println("catch: " + i);
} finally {
i++;
System.out.println("finally: " + i);
}
return i;
}
}
// try: 2
// finally: 3
// 2引用类型:
public static void main(String[] args) {
System.out.println(testReturn2());
}
public static List<Integer> testReturn2() {
List<Integer> list = new ArrayList<>();
try {
list.add(1);
System.out.println("try: " + list);
return list;
} catch (Exception e) {
list.add(2);
System.out.println("catch: " + list);
} finally {
list.add(3);
System.out.println("finally: " + list);
}
return list;
}
// try: [1]
// finally: [1, 3]
// [1, 3]2.2 catch中带return的
public static void main(String[] args) {
System.out.println(testReturn3());
}
public static int testReturn3() {
int i = 1;
try {
i++;
System.out.println("try: " + i);
int x = i / 0;
} catch (Exception e) {
i++;
System.out.println("catch: " + i);
return i;
} finally {
i++;
System.out.println("finally: " + i);
}
return i;
}
// try: 2
// catch: 3
// finally: 4
// 32.3 finally中带return的
public static void main(String[] args) {
System.out.println(testReturn4());
}
public static int testReturn4() {
int i = 1;
try {
i++;
System.out.println("try: " + i);
return i;
} catch (Exception e) {
i++;
System.out.println("catch: " + i);
} finally {
i++;
System.out.println("finally: " + i);
return i;
}
}
//try: 2
//finally: 3
//3finally中的代码总会执行
当try、catch中有return时,也会执行finally。return的时候,要注意返回值的类型,是否收到finally中代码的影响
finally中有return时,会直接在finally中退出,导致try、catch中的return失效
————————————————
版权声明:本文为CSDN博主「橙子19911016」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xingyu19911016/article/details/120487026

0条评论
点击登录参与评论