java 关键字finally的用法

时间:2023-01-14 18:18:59

只有一种情况finally中的代码不会执行,前面有System.exit(0) 或者 System.exit(1)

1、System.out.println("=========================");语句不会执行

public class ExceptionTest {
public static void main(String[] args) {

try{
throw new Exception();
} catch(Exception e){
System.exit(0);
} finally {
System.out.println("=========================");
}
}
}

2、 System.out.println("=========================");语句执行

前面的return语句,下面的finally也会执行

public class ExceptionTest {
public static void main(String[] args) {

try{
throw new Exception();
} catch(Exception e){
//System.exit(1);
return;
} finally {
System.out.println("=========================");
}
}
}