请写出下列程序的运行结果:
public static String exce(String a, String b) {
try {
return a + "+" + b;
} catch (Exception e) {
System.out.println("I'm Exception");
}finally {
System.out.println("I'm will execute");
}
return b;
}
public static void main(String[] args) {
System.out.println(exce(null,"hello"));
}
答案:
I'm will execute
null+hello
首先我们先来看程序的运行过程,这个程序没有出错,不会抛出异常,main方法调用exce方法之后先执行try语句块里面的代码,没发生异常,则执行finally里的代码,最后最后返回的是try语句块里的结果,程序并不会执行exce方法后面的return语句。
public static String exce(String a, String b) {
try {
return a + "+" + b;
} catch (Exception e) {
System.out.println("I'm Exception");
}finally {
System.out.println("I'm will execute");
}
return b;
}
public static void main(String[] args) {
System.out.println(exce(null,"hello"));
}
运行结果:
I'm will execute
null+hello
如果try代码块有return语句,发生异常,而catch代码块里没有return语句,则返回的是整个方法的后面return结果
public static String exce(String a, String b) {
try {
int[] array = {1,2,3,4,};
for (int i = 0; i < 5; i++) {
System.out.println(array[i]);
}
return a + "+" + b;
} catch (Exception e) {
System.out.println("I'm Exception");
}finally {
System.out.println("I'm will execute");
}
return b;
}
public static void main(String[] args) {
System.out.println(exce(null,"hello"));
}
运行结果:
1
2
3
4
I'm Exception
I'm will execute
hello
如果try代码块有return语句,发生异常,而catch代码块里也有return语句则返回的是catch代码块的结果;
public static String exce(String a, String b) {
try {
int[] array = {1,2,3,4,};
for (int i = 0; i < 5; i++) {
System.out.println(array[i]);
}
return a + "+" + b;
} catch (Exception e) {
System.out.println("I'm Exception");
return "返回exception";
}finally {
System.out.println("I'm will execute");
}
}
public static void main(String[] args) {
System.out.println(exce(null,"hello"));
}
运行结果:
1
2
3
4
I'm Exception
I'm will execute
返回exception
只要finally代码块有return语句,都返回finally代码块的结果。:
public static String exce(String a, String b) {
try {
int[] array = {1,2,3,4,};
for (int i = 0; i < 5; i++) {
System.out.println(array[i]);
}
return a + "+" + b;
} catch (Exception e) {
System.out.println("I'm Exception");
return "返回exception";
}finally {
System.out.println("I'm will execute");
return b;
}
}
public static void main(String[] args) {
System.out.println(exce(null,"hello"));
}
运行结果:
1
2
3
4
I'm Exception
I'm will execute
hello
总结:
1、如果try代码块有return语句,没有发生异常,并且finally代码块里没有return语句则返回try代码块的结果;
2、如果try代码块有return语句,发生异常,而catch代码块里也有return语句则返回的是catch代码块的结果;
3、如果try代码块有return语句,发生异常,而catch代码块里没有return语句,则返回的是整个方法的后面return结果;
4、只要finally代码块有return语句,都返回finally代码块的结果。
注意:
1、如果catch代码块或者finally代码块里有了return语句则不能在该方法后面再写return语句;
这两种情况都会报错!
---------------------------------------------------------------------------------分割线------------------------------------------------------------------------------------------
关于null的问题:
在前面的那道面试题里,可能我们会有疑问,为什么传了一个空值进去,不仅不报错还输出了字符串null,其实是因为java里面有一个方法:当我们把String的值赋值为null的话,在这个方法里面会进行判断,如果等于null则会把null转化为字符串:“null”,这就是为什么传null进去会输出字符串“null”的原因。