try catch 和方法中都有返回
public class MainTest {
public static void main(String[] args) {
System.out.println("测试结果 " + test(true));
}
static String test(boolean exception){
try {
System.out.println("start");
if(exception){
throw new Exception(new RuntimeException());
}
return "try";
} catch (Exception e){
System.out.println("Exception");
e.printStackTrace();
return "Exception";
} finally {
System.out.println("finally");
//return "finally";
}
return "test";
}
}
不允许这样写,运行时会报“错误: 无法访问的语句 return “test”;
当try 和catch 中都有返回时,方法是不允许有return,因为代码不会执行到try catch之外。
try 和方法中都有返回
public class MainTest {
public static void main(String[] args) {
System.out.println("测试结果 " + test(true));
}
static String test(boolean exception){
try {
System.out.println("start");
if(exception){
throw new Exception(new RuntimeException());
}
return "try";
} catch (Exception e){
System.out.println("Exception");
e.printStackTrace();
// return "Exception";
} finally {
System.out.println("finally");
//return "finally";
}
System.out.println("最后一行");
return "finish";
}
}
结果
start
Exception
finally
最后一行
测试结果 finish
java.lang.Exception: java.lang.RuntimeException
at com.example.testdemo.MainTest.test(MainTest.java:12)
at com.example.testdemo.MainTest.main(MainTest.java:5)
Caused by: java.lang.RuntimeException
... 2 more
1.方法执行完毕后抛出异常
2.先进入到catch中,然后是finally,最后执行方法return
finally和方法中都有return
public class MainTest {
public static void main(String[] args) {
System.out.println("测试结果 " + test(true));
}
static String test(boolean exception){
try {
System.out.println("start");
if(exception){
throw new Exception(new RuntimeException());
}
//return "try";
} catch (Exception e){
System.out.println("Exception");
e.printStackTrace();
//return "Exception";
} finally {
System.out.println("finally");
return "finally";
}
System.out.println("最后一行");
return "finish";
}
}
无法执行,因为finally一定会被执行,方法的return无法执行
try catch 和finally中都有return
public class MainTest {
public static void main(String[] args) {
System.out.println("测试结果 " + test(false));
}
static String test(boolean exception){
try {
System.out.println("start");
if(exception){
throw new Exception(new RuntimeException());
}
return "try";
} catch (Exception e){
System.out.println("Exception");
e.printStackTrace();
return "Exception";
} finally {
System.out.println("finally");
return "finally";
}
// System.out.println("最后一行");
// return "finish";
}
}
start
finally
测试结果 finally
最终执行finally中的return