Java中的try catch finaly先后调用顺序

时间:2023-03-08 23:02:32
Java中的try catch finaly先后调用顺序

自我总结,有什么不足或好的方案,希望大家给予纠正,感激不尽!

目的:try catch finaly的顺序执行,和大家复习一遍。

方法:debug来确认执行顺序。(需要引入junit包)

废话不多说,debug是检验代码执行顺序的唯一标准,哈哈...

测试一:

新建测试类:ExceptionTest

package com.core.test007;

import org.junit.Test;

public class ExceptionTest {

    @Test
public void main(){
put(test007());
} public int test007(){
int a = 10;
put("normal");
try {
put("try");
// a = 1 / 0;
put("try return before");
return a;
}catch (Exception e){
put("catch"); } finally {
put("finally");
}
put("method return before");
return 0;
} public static void put(Object obj) {
System.out.println(obj);
} }

打印出的信息为

normal
try
try return before
finally
10

debug了一下 ,执行语句的顺序为:

  1)  try体的语句,打印"try"

  2)  在try体中,打印 "try return before"

  3)  跳入finaly体,打印"finaly"

  4)  再次执行try体中的return语句

  5)  直接跳出函数体 返回到主函数体,打印 10

测试二:  

将上述ExceptionTest类代码中[ int a = 1 / 0 ; ]之前的注释删除,保存再次run则打印的信息为:

normal
try
catch
finally
method return before
0

debug了一下 ,执行语句的顺序为:

  1)  try体的语句,打印 "try"

  2) 执行语句 [ int a = 1 / 0 ; ]时,进入catch体,打印 "catch"

  3)  跳入finaly体,打印 "finaly"

  5)  跳出finaly体,打印 "method return before"

  6)  执行return 0

  7)  返回主函数,打印 0

总结:1. finaly体任何情况下都会执行。

     2. 当执行到try体中存在异常的语句(本案例中的异常语句为:[ int a = 1 / 0 ; ])时,则在try体中异常语句之后的语句在本次执行过程中都不会再被执行,而是进入catch语句。