码迷,mamicode.com
首页 > 编程语言 > 详细

Java牛角尖【007】:Java中的Error能不能被Catch

时间:2017-09-18 01:18:00      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:under   view   很多   tail   com   执行   r.java   xtend   blank   

  Java牛角尖【007】:Java中的Error能不能被Catch

网上看到很多朋友说Java中Error是无法Catch到的,而Java中定义的Error类型又很难测试到,那就估且以为确是如此吧。

但是或许大家都有注意,我们时常会看到这样的代码

 

 

[java] view plain copy
 
  1. try{  
  2.     ...  
  3. }catch(Throwable ex){  
  4.     ...  
  5. }  

 

 

其中catch中直接捕捉的是一个Throwable类,打开继承关系看一下,Exception和Error两个类同样是从Throwable类继承而来,那么,也就是说Error应该是可以被捕捉的,下面写个例子证明一下猜测:

 

 

[java] view plain copy
 
  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一样是可以捕捉的,运行代码结果为:

 

 

[xhtml] view plain copy
 
  1. 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)

 

Java牛角尖【007】:Java中的Error能不能被Catch

标签:under   view   很多   tail   com   执行   r.java   xtend   blank   

原文地址:http://www.cnblogs.com/timdes1/p/7538906.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!