try、catch、finally用法总结
try、catch、finally用法总结
- 无论是否存在异常,finally代码块中的代码都会执行。
- try代码块中的代码,出现异常的代码之后不会执行。
- 如果方法存在返回值,那么会先运算return,然后在运行finally代码块。
- 如果finally代码块中存在return语句,那么程序会提前退出,并且不返回try或者catch代码块中的值。
一:不存在返回值,没有异常信息。
public static void main(String[] args) {
test01();
System.out.println("test01 method the end");
}
public static void test01() {
int num = 0;
try {
num ++;
System.out.println("Try the end, num = " + num);
} catch (Exception e) {
num ++;
System.out.println("Catch the end, num = " + num);
} finally {
num ++;
System.out.println("Finally the end, num = " + num);
}
}
控制台结果输出
Try the end, num = 1
Catch the end, num = 2
test01 method the end
二:方法存在返回值,无异常信息
public static void main(String[] args) {
System.out.println("test_01 method the end, num = " + test_01());
}
public static int test_01() {
int num = 0;
try {
num ++;
System.out.println("Try the end, num = " + num);
return num;
} catch (Exception e) {
num ++;
System.out.println("Catch the end, num = " + num);
return num;
} finally {
num ++;
System.out.println("Finally the end, num = " + num);
}
}
控制台结果输出
Try the end, num = 1
Finally the end, num = 2
test_01 method the end, num = 1
三:finally代码块中存在return
public static void main(String[] args) {
System.out.println("test_01 method the end, num = " + test_01());
}
public static int test_01() {
int num = 0;
try {
num ++;
System.out.println("Try the end, num = " + num);
return num;
} catch (Exception e) {
num ++;
System.out.println("Catch the end, num = " + num);
return num;
} finally {
num ++;
System.out.println("Finally the end, num = " + num);
return num;
}
}
控制台结果输出
Try the end, num = 1
Finally the end, num = 2
test_01 method the end, num = 2
学习是一个循序渐进的过程