java异常没有catch住,Java异常没有被捕获

Why are some exceptions in Java not caught by catch (Exception ex)? This is code is completely failing out with an unhandled exception. (Java Version 1.4).

public static void main(String[] args) {

try {

//Code ...

} catch (Exception ex) {

System.err.println("Caught Exception");

ex.printStackTrace();

exitCode = app.FAILURE_EXIT_CODE;

}

finally {

app.shutdown();

}

System.exit(exitCode);

}

I get a Exception in thread "main" java.lang.NoSuchMethodError

But this works

public static void main(String[] args) {

int exitCode = app.SUCCESS_EXIT_CODE;

try {

//Code ...

} catch (java.lang.NoSuchMethodError mex){

System.err.println("Caught NoSuchMethodError");

mex.printStackTrace();

exitCode = app.FAILURE_EXIT_CODE;

} catch (Exception ex) {

System.err.println("Caught Exception");

ex.printStackTrace();

exitCode = app.FAILURE_EXIT_CODE;

}

finally {

app.shutdown();

}

System.exit(exitCode);

}

I get Caught NoSuchMethodError java.lang.NoSuchMethodError:

I thought catching exceptions would catch all exceptions? How can I catch all exceptions in java?

解决方案

Because some exceptions don't derive from Exception - e.g. Throwable and Error.

Basically the type hierarchy is:

Object

|

Throwable

/ \

Exception Error

Only Throwables and derived classes can be thrown, so if you catch Throwable, that really will catch everything.

Any exception deriving from Exception (or Exception itself) other than those derived from RuntimeException count as checked exceptions - they're the ones that you have to declare you'll throw, or catch if you call something that throws them.

All told, the Java exception hierarchy is a bit of a mess...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值