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 没有输出来呢?
System.out.println("IN method2 run ");不会抛出异常的。
后面的catch (Exception e) {
System.out.println("In method2 exception="+e);
e.printStackTrace();
加上throw e
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) {
// e.printStackTrace();
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 t) {
System.out.println("In method2 exception=" + t);
t.printStackTrace();
}
} public static void main(String[] args) {
TestTryCatch tt = new TestTryCatch ();
try {
tt.method2();
} catch (Exception e) {
e.printStackTrace();
}
}}