可我上面的程序没有错误,扑捉到了异常,程序运行结果是: This is the main catch
晕,你打印当然还是打印你那句话了啊。你catch到异常后用e.printStack()就可以看到效果了public class Excepts { public static void func1() throws Throwable { throw new Exception("from func1"); } public static void main(String[] Str) throws Throwable { try { func1(); } // catch (Exception e) catch (Throwable e) { e.printStackTrace(); System.out.println("This is the main catch"); } }} 打印: java.lang.Exception: from func1 at com.withiter.test2.Excepts.func1(Excepts.java:5) at com.withiter.test2.Excepts.main(Excepts.java:10) This is the main catch
public class Excepts { public static void func1() throws Throwable { throw new Throwable ("from func1"); }
public static void main(String[] Str) throws Throwable { try { func1(); } catch (Exception e) // catch (Throwable e) { e.printStackTrace(); System.out.println("This is the main catch"); } }
类型如果是向下转换的,接收的时候要转换过来:(Exception)Throwable 再例如: Object o ="aaaaaaaaa"; ((String)Object).subString(...);
类型如果是向下转换的,接收的时候要转换过来:(Exception)Throwable 再例如: Object o ="aaaaaaaaa"; ((String)o).subString(...);
try中抛出的是Throwable异常,但是catch(Exception e)捕捉到了异常,这是何解我只是想说明Throwable,Exception 的关系范围,这里catch(Exception e)并未捕获到,System.out.println("This is the main catch");这都没执行
可我上面的程序没有错误,扑捉到了异常,程序运行结果是: This is the main catch方法声明了异常A,那么调用者必须捕捉A(RuntimeException除外),仅仅捕捉子异常是不能通过编译的。
try中抛出的是Throwable异常,但是catch(Exception e)捕捉到了异常,这是何解我只是想说明Throwable,Exception 的关系范围,这里catch(Exception e)并未捕获到,System.out.println("This is the main catch");这都没执行 你修改了我的程序,你说的这些关系范围我知道,不过还是谢谢你的详细解释
This is the main catch
This is the main catch
public static void func1() throws Throwable {
throw new Exception("from func1");
} public static void main(String[] Str) throws Throwable {
try {
func1();
}
// catch (Exception e)
catch (Throwable e)
{
e.printStackTrace();
System.out.println("This is the main catch");
}
}}
打印:
java.lang.Exception: from func1
at com.withiter.test2.Excepts.func1(Excepts.java:5)
at com.withiter.test2.Excepts.main(Excepts.java:10)
This is the main catch
public static void func1() throws Throwable {
throw new Throwable ("from func1");
}
public static void main(String[] Str) throws Throwable {
try {
func1();
}
catch (Exception e)
// catch (Throwable e)
{
e.printStackTrace();
System.out.println("This is the main catch");
}
}
}
这样就必须平抛了
2.编译器有责任,你写的也不当。方法里面不会抛出东西,你在方法头上抛出干什么。如果你按照正确的使用了,编译除了问题,那编译器就说不过去了。编译期检查可以是有限的。
3.func1()方法的写法是不典范的。一般来说,类型应该是向上转换的,就像数值类型的自动隐式转换。也就是说应该父类变成子类,倒过来回丢失成员的,发生不可预料的问题。
再例如:
Object o ="aaaaaaaaa";
((String)Object).subString(...);
再例如:
Object o ="aaaaaaaaa";
((String)o).subString(...);
This is the main catch方法声明了异常A,那么调用者必须捕捉A(RuntimeException除外),仅仅捕捉子异常是不能通过编译的。
你修改了我的程序,你说的这些关系范围我知道,不过还是谢谢你的详细解释