public class Test1{
public String testt() throws Exception{
try {
int i = 9/0;
} catch (Exception e) {
throw e;
}finally{
return "test1";
}
}
}
public class Test2 {
public static void main(String[] args) {
Test1 t = new Test1();
String str = "test2";
try{
str = t.testt();
System.out.println(str);
}catch(Exception e){
System.out.println(str);
}
}
}
上述代码输出“test1”,有没有大神出来解释下为什么Test2里面的catch没有进去?
你的testt()方法写了finally的,finally是无论如何都会执行的代码块,对于Test2 中的str 得到值的过程并没有出现异常,所以不会进入到catch代码块里面的
testt()方法内部把异常捕获处理了 所以你调用的时候test2不会进入catch
因为对str获取的值没有任何影响(”i“没有使用),所以这个错误就自动忽略了。
finally 语句块是在这些控制转移语句之前执行,catch exception 也属于控制权转移(接下来会退出testt方法,把控制权交给main函数),所以,return 会覆盖throw excetion 。
再者仔细想想一个方法一边返回值,一边抛出异常,根本没有这种操作的,finally语句也不要这么去用
第一个类的testtt方法finally的部分即使抛出异常最终也会执行,并且return你给的test1,在第二个类里面,你是新建的test1对象调的testtt方法,得到这个方法的返回值test1是没有错的,此时已经抛完这个方法的异常走完调用了,接下来是正常输出,没有捕获到异常,当然不会走test2的catch部分了。