java try-catch
/**
* @author wang
* @description 直接复制下来运行。
* @create 2022/3/4 15:14
*/
public class TTT {
public static int sum1() {
int firstNum = 1;
int secondNum = 2;
int result = 0;
try {
//计算结果
result = firstNum + secondNum;
return result;
} finally {
System.out.println("sum1() finally块被执行了!");
}
}
public static int sum2() {
int firstNum = 1;
int secondNum = 2;
int result = 0;
try {
//计算结果
result = firstNum + secondNum;
return result;
} finally {
System.out.println("sum2() finally块被执行了!");
result = 777;
}
}
public static int sum3() {
int firstNum = 1;
int secondNum = 2;
int result = 0;
try {
result = firstNum + secondNum;
return result;
} finally {
System.out.println("sum3() finally块被执行了!");
result = 7;
return result;
}
}
public static int sum4() {
int firstNum = 1;
int secondNum = 2;
int result = 0;
try {
//计算结果
result = firstNum + secondNum;
//制造异常
int i = 1 / 0;
return result;
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
System.out.println("sum4() finally块被执行了!");
result = 7;
return result;
}
}
public static int sum5() {
int firstNum = 1;
int secondNum = 2;
int result = 0;
try {
//计算结果
result = firstNum + secondNum;
//系统退出,,,finally不再执行
System.exit(1);
return result;
} finally {
System.out.println("sum5() finally块被执行了!");
result = 7;
return result;
}
//编译器会报错,因为无法执行到此处
//return 1111;
}
public static void main(String[] args) {
System.out.println(TTT.sum1());
System.out.println(TTT.sum2());
System.out.println(TTT.sum3());
System.out.println(TTT.sum4());
System.out.println(TTT.sum5());
//结论:
//try { return A }catch{ }finally{ } 原引用为A,会”备份“A,记为B (A,B都在栈上)
// 当A是基本类型时,不管你如何对A进行操作,返回的是B的值,除非你在fianlly中 也return A 则B值会被更新。
//当A是引用类型。你备份的B和A指向的是堆中同一块内存,你用A任意引用操作对象,返回的都是更改后的同一个对象。
}
}
运行结果:
sum1() finally块被执行了!
3
sum2() finally块被执行了!
3
sum3() finally块被执行了!
7
/ by zero
sum4() finally块被执行了!
7