使用前提
try语句用于捕获程序运行时候的异常,防止throws在一直都抛给上一层的方法或者类,那么一般是用try语句来处理java代码中会出现的一异常的,那如果三个代码块中都存在return程序会怎么运行代码结果呢
代码测试
1、方法返回值类型是string,三个代码块中都存在return
//测试try和catch、finally中return的效果
public static void main(String[] args) {
tryCatchFinallyTest();
System.out.println("-------------------");
String s = tryCatchFinallyTest();
System.out.println(s);
}
public static String tryCatchFinallyTest(){
try {
System.out.println("try的第一个方法");
return "try的第一个结束方法";
}catch (Exception e){
System.out.println("catch的第一个方法");
return "catch的第一个结束方法";
}finally {
System.out.println("finally的第一个方法");
return "finally的第一个结束方法";
}
}
运行结果
try和finally中的语句都运行了,try语句中finally语句是一定会运行的,catch中是需要遇到异常才可以运行的代码块,所以try中没有异常的话,就不会执行但是最后这个方法的返回的是finally中return出来String结果
2、try中没有return语句
//测试try和catch、finally中return的效果
public static void main(String[] args) {
// tryCatchFinallyTest();
System.out.println("-------------------");
String s = tryCatchFinallyTest();
// System.out.print(s);
}
public static String tryCatchFinallyTest(){
try {
System.out.println("try的第一个方法");
}catch (Exception e){
System.out.println("catch的第一个方法");
return "catch的第一个结束方法";
}finally {
System.out.println("finally的第一个方法");
return "finally的第一个结束方法";
}
}
运行结果
3、try中有return,finally中没有
//测试try和catch、finally中return的效果
public static void main(String[] args) {
tryCatchFinallyTest();
System.out.println("-------------------");
String s = tryCatchFinallyTest();
System.out.print(s);
}
public static String tryCatchFinallyTest(){
try {
System.out.println("try的第一个方法");
return "try的第一个结束方法";
}catch (Exception e){
System.out.println("catch的第一个方法");
return "catch的第一个结束方法";
}finally {
System.out.println("finally的第一个方法");
// return "finally的第一个结束方法";
}
}
运行结果
4、存在异常的捕获
//测试try和catch、finally中return的效果
public static void main(String[] args) {
tryCatchFinallyTest();
System.out.println("-------------------");
String s = tryCatchFinallyTest();
System.out.print(s);
}
public static String tryCatchFinallyTest(){
try {
System.out.println("try的第一个方法");
System.out.println(1/0);
return "try的第一个结束方法";
}catch (Exception e){
System.out.println("catch的第一个方法");
return "catch的第一个结束方法";
}finally {
System.out.println("finally的第一个方法");
return "finally的第一个结束方法";
}
}