先执行try,出现错误执行catch,程序最终都会执行finlly:
主方法:
public static void main(String[] args) {
System.out.println(test());
}
一:不出错执行顺序
public static String test() {
try {
System.out.println("try的输出");
return "try的返回";
} catch (Exception e) {
System.out.println("catch的输出");
return "catch的返回";
} finally {
System.out.println("finally的输出");
}
}
//当有return时,没有出错的情况下执行完try在执行finlly
(console:try的输出finally的输出try的返回)
二:
public static String test() {
try {
System.out.println("try的输出");
if(true){
throw new RuntimeException("出错了");
}
System.out.println("出错后try的输出");
return "try的返回";
} catch (Exception e) {
System.out.println("catch的输出");
return "catch的返回";
} finally {
System.out.println("finally的输出");
}
//当出现错误时,先执行try之前未出错的内容,然后执行catch,然后执行finlly的内容,在回去执行catch的return;(不会再执行try的return,程序在出错后不会再执行,望知晓)
(console:try的输出catch的输出finally的输出catch的返回)
关于执行catch后,try-catch后面代码的执行情况:
三: public static String test() {
try {
System.out.println("try的输出");
if (true) {
throw new RuntimeException("出错了");
}
System.out.println("出错后try的输出");
} catch (Exception e) {
System.out.println("catch的输出");
// return "catch的返回";
} finally {
System.out.println("finally的输出");
// return "finally的返回";
}
System.out.println("后面代码的输出");
return "1";
}
(在catch和finnally中并没有抛出异常并且没有return结束方法,
所以后面的代码会有输出,
CONSLOLE:try的输出catch的输出finally的输出后面代码的输出1)
四:public static String test() {
try {
System.out.println("try的输出");
if (true) {
throw new RuntimeException("出错了");
}
System.out.println("出错后try的输出");
} catch (Exception e) {
System.out.println("catch的输出");
return "catch的返回";
} finally {
System.out.println("finally的输出");
}
System.out.println("后面代码的输出");
return "1";
}
(当在catch里面加入return时编译并不会报错,因为catch不是必执行
语句,注意后面需要return(如: return "1";),此时输出则是:
CONSOLE:try的输出catch的输出finally的输出,catch的返回---》》可以看出后面代码并没有执行,因为在catch中已经进行return)
五:
String test() {
try {
System.out.println("try的输出");
if (true) {
throw new RuntimeException("出错了");
}
System.out.println("出错后try的输出");
} catch (Exception e) {
System.out.println("catch的输出");
return "catch的返回";
} finally {
System.out.println("finally的输出");
return "finally的返回";
}
}
CONSOLE:
try的输出
catch的输出
finally的输出
finally的返回