java异常之返回值
java发生异常之后在try里写了返回值,在finally里也写了返回值,得到的返回值是什么呢?
package Test;
public class TestException {
public static void main(String[] args) {
System.out.println(getname());
}
public static String getname() {
try{
System.out.println("执行到try");
Integer.parseInt("test");
return "try";
}
catch(Exception e){
System.out.println("执行到catch");
return "catch";
}
finally {
System.out.println("执行到finally");
return "finally";
}
}
}
看下输出的结果:
如果没有发生异常,在try和finally里面都写return,返回值是什么呢?
package Test;
public class TestException {
public static void main(String[] args) {
System.out.println(getname());
}
public static String getname() {
try{
System.out.println("执行到try");
return "try";
}
catch(Exception e){
System.out.println("执行到catch");
}
finally {
System.out.println("执行到finally");
return "finally";
}
}
}
你可能觉得try里面的return没有执行,那么我们这样改:
package Test;
public class TestException {
public static void main(String[] args) {
System.out.println(getname());
}
public static String getname() {
try{
System.out.println("执行到try");
return "try";
}
catch(Exception e){
System.out.println("执行到catch");
}
finally {
System.out.println("执行到finally");
}
return "finally";
}
}
我们可以看到try里面的return确实执行了。而且finally语句也执行了。函数值一旦返回不就结束这个函数的执行了么?
这个确实如此。不过在异常处理中。当try或者catch中有return后,会直接把return的语句放到finally中。而且如果
finally中如果有return,会覆盖try或者catch中的return。这是无论是否发生异常和在try,catch里写返回值之后finally都
会执行的原因。