网上看到很多朋友说Java中Error是无法Catch到的,而Java中定义的Error类型又很难测试到,那就估且以为确是如此吧。
但是或许大家都有注意,我们时常会看到这样的代码
- 1. try{
- 2. ...
- 3. }catch(Throwable ex){
- 4. ...
- 5. }
其中catch中直接捕捉的是一个Throwable类,打开继承关系看一下,Exception和Error两个类同样是从Throwable类继承而来,那么,也就是说Error应该是可以被捕捉的,下面写个例子证明一下猜测:
- 1. package net.moon.demo.errorcatch;
- 2.
- 3. public class Demo {
- 4.
- 5. /**
- 6. * @param args
- 7. */
- 8. public static void main(String[] args) {
- 9. // TODO Auto-generated method stub
- 10. try {
- 11. throw new MyError("My Error");
- 12. } catch (MyError e) {
- 13. System.out.println(e.getMessage());
- 14. }
- 15. }
- 16.
- 17. }
- 18.
- 19. class MyError extends Error {
- 20.
- 21. /**
- 22. *
- 23. */
- 24. private static final long serialVersionUID = 1L;
- 25.
- 26. public MyError() {
- 27. super();
- 28. // TODO Auto-generated constructor stub
- 29. }
- 30.
- 31. public MyError(String message, Throwable cause) {
- 32. super(message, cause);
- 33. // TODO Auto-generated constructor stub
- 34. }
- 35.
- 36. public MyError(String message) {
- 37. super(message);
- 38. // TODO Auto-generated constructor stub
- 39. }
- 40.
- 41. public MyError(Throwable cause) {
- 42. super(cause);
- 43. // TODO Auto-generated constructor stub
- 44. }
- 45.
- 46. }
执行一下以上代码,正如前面的猜测,Error一样是可以捕捉的,运行代码结果为:
- My Error