1、如果try,catch,finally里面都没有return语句,正常执行顺序如下:
try代码块正常执行完成,继续执行finally代码块,最后执行finally后面的语句块;
try代码块执行出现异常,则转去执行catch块,catch块执行完后,再执行finally代码块,最后执行finally后面的语句块。
public class Main {
static String str="";
public static void main(String[] args) {
//Scanner scanner = new Scanner(System.in);在线笔试代码用
test(0);
System.out.println(str);
str="";
test(1);
System.out.println(str);
}
private static void test(int i){
try{
if(i==1)
throw new Exception();
else {
str+="111-";
//return;
}
}catch (Exception e){
str+="222-";
//return;
}finally {
str+="333-";
//return;
}
str+="444";//Unreacheable statement
}
}
输出结果:<code class="language-java">111-333-444
222-333-444
2、(1)如果finally里面有return,不管try、catch里面有没有return,finally语句块后面的代码都不会执行,编译器都会提示错误:Unreachable statement。
public class Main {
static String str="";
public static void main(String[] args) {
//Scanner scanner = new Scanner(System.in);在线笔试代码用
test(0);
System.out.println(str);
str="";
test(1);
System.out.println(str);
}
private static void test(int i){
try{
if(i==1)
throw new Exception();
else {
str+="111-";
//return;
}
}catch (Exception e){
str+="222-";
//return;
}finally {
str+="333-";
return;
}
str+="444";//Unreacheable statement
}
}
(2)如果try、catch块里面都有return,不管finally里面有没有return,finally语句块后面的代码都不会执行,编译器都会提示错误:Unreachable statement。
public class Main {
static String str="";
public static void main(String[] args) {
//Scanner scanner = new Scanner(System.in);在线笔试代码用
test(0);
System.out.println(str);
str="";
test(1);
System.out.println(str);
}
private static void test(int i){
try{
if(i==1)
throw new Exception();
else {
str+="111-";
return;
}
}catch (Exception e){
str+="222-";
return;
}finally {
str+="333-";
//return;
}
str+="444";//Unreacheable statement
}
}
3、不管try、catch、finally里面有没有return,都会执行的组合是:try-finally 或者 try-catch-finally。如下代码中3处标记行号地方,每一个不管用咩用,都不影响最终输出结果。
public class Main {
static String str="";
public static void main(String[] args) {
//Scanner scanner = new Scanner(System.in);在线笔试代码用
test(0);
System.out.println(str);
str="";
test(1);
System.out.println(str);
}
private static void test(int i){
try{
if(i==1)
throw new Exception();
else {
str+="111-";
return;//1
}
}catch (Exception e){
str+="222-";
return;//2
}finally {
str+="333-";
return;//3
}
//str+="444";//Unreacheable statement
}
}
输出结果:
4、在返回值方面,finally里面的return值会覆盖try、catch里面的return值。
/**
* 测试问题:在返回值方面:finally里面的return值会覆盖try,catch里面的return值
* @param num
* @return
*/
static int getNum(int num){
try{
int result=2/num;
return result;
}catch(Exception e){
return 0;
}finally {
if(num==0)
return -1;
if(num==1)
return 1;
}
}
}
输出结果:
<code class="language-html">-1
1
1
0