网上看到很多朋友说Java中Error是无法Catch到的,而Java中定义的Error类型又很难测试到,那就估且以为确是如此吧。
但是或许大家都有注意,我们时常会看到这样的代码
[java] view plain copy
- try{
- ...
- }catch(Throwable ex){
- ...
- }
其中catch中直接捕捉的是一个Throwable类,打开继承关系看一下,Exception和Error两个类同样是从Throwable类继承而来,那么,也就是说Error应该是可以被捕捉的,下面写个例子证明一下猜测:
[java] view plain copy
- package net.moon.demo.errorcatch;
- public class Demo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- try {
- throw new MyError("My Error");
- } catch (MyError e) {
- System.out.println(e.getMessage());
- }
- }
- }
- class MyError extends Error {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public MyError() {
- super();
- // TODO Auto-generated constructor stub
- }
- public MyError(String message, Throwable cause) {
- super(message, cause);
- // TODO Auto-generated constructor stub
- }
- public MyError(String message) {
- super(message);
- // TODO Auto-generated constructor stub
- }
- public MyError(Throwable cause) {
- super(cause);
- // TODO Auto-generated constructor stub
- }
- }
执行一下以上代码,正如前面的猜测,Error一样是可以捕捉的,运行代码结果为:
[xhtml] view plain copy
- My Error
下面给个小例子,来验证一下error的捕获。
复制代码代码如下:
public class TestCatchError extends Error{
private static final long serialVersionUID = -351488225420878020L;
public TestCatchError(){
super();
}
public TestCatchError(String msg){
super(msg);
}
public static void main(String[] args) {
try {
throw new TestCatchError("test catch error");
} catch (Throwable t) {
System.out.println("step in the catch ~");
t.printStackTrace();
}
}
}
运行结果:
复制代码代码如下:
step in the catch ~
TestCatchError: test catch error
at TestCatchError.main(TestCatchError.java:23)