一.finally的作用
- 在try-catch捕获异常语句后还可以加上finally语句块
- 作用:finally不论是否抛出异常都会执行,即使在有返回值并且已执行return语句后,也会执行finally语句块,但return返回的结果不会改变
- 示例:在抛出异常的情况下
/**
* @ Author: Zhangyu
* @ Date: 2020/7/27
* @ Description:
*/
public class Test {
public static void main(String[] args) {
try {
int num=1/0;
System.out.println(num);
}catch (ArithmeticException e){
System.out.println("除数不能为零");;
}finally {
System.out.println("我是finally");
}
}
}
输出结果:
除数不能为零
我是finally
- 示例:在不抛出异常的情况下
/**
* @ Author: Zhangyu
* @ Date: 2020/7/27
* @ Description:
*/
public class Test {
public static void main(String[] args) {
try {
int num=1/1;
System.out.println(num);
}catch (ArithmeticException e){
System.out.println("除数不能为零");;
}finally {
System.out.println("我是finally");
}
}
}
输出结果:
1
我是finally