public class TestTryCatch {
private boolean method1() throws Exception{
boolean have = false;
try{
String[] str1 = {"123","456"};
System.out.println("" +str1[3]);
have = true;
}catch(Exception e){
System.out.println("In method1 This is exception= "+e);
throw e;
}finally{
have = true;
return have;
}
} private void method2(){
try {
if(method1()){
System.out.println("IN method2 run ");
}
} catch (Exception e) {
System.out.println("In method2 exception="+e);
e.printStackTrace();
}
} public static void main(String[] args) {
TestTryCatch tt = new TestTryCatch();
try {
tt.method2();
} catch (Exception e) {
e.printStackTrace();
}
}}输出:
In method1 This is exception= java.lang.ArrayIndexOutOfBoundsException: 3
IN method2 run 问一下?
为什么 In method2 exception 没有输出来呢?
--------------
否则报错
最后有finally{
have = true;
return have;
}
不会抱错的:),你可以试一下
首先建立TestTryCatch的对象tt,然后调用method2()方法.下面是执行method2().
一句一句来,先try{}catch语句,在它之中是if语句,if语句调用method1()方法.
接下来去执行method1()函数,在你的menthod1()中,主体是try{}catch{}finally
语句,相信你一定知道,finally特性,所以最终method1返回的是true.这也就决定
在method2()的try不会抛出异常而输出 IN method2 run