java 异常

示例:设计一个异常类,然后抛出并捕获它,代码如下:

 1 import java.lang.Exception.*;
 2 
 3 class testException extends Exception
 4 {
 5     public testException(String exceptionInfo) {
 6         super(exceptionInfo);
 7     }
 8 
 9     public testException() {}
10 }
11 
12 public class ExceptionDemo
13 {
14     public static void main(String[] args) {
15         //throw new testException();
16         try{
17             testException1();
18         }catch(Exception testException) {
19             System.out.println("testException1");
20         }
21     }
22 
23     public static void testException1() throws testException{
24         throw new testException();
25     }
26 }

 

 

 

在进行异常的抛出时,如果你希望抛出一个更高级的异常而又不丢失原始异常的信息时,可以采用如下做法

 

 

 1 try {
 2 
 3   //access the database
 4 
 5 }catch(SQLException) {
 6 
 7   //sometime you just want to write the exception into the log
 8 
 9   //logger.log(level, message, e);
10 
11   Throwable se = new ServletException("error..");
12 
13   se.initCause(e);
14 
15       throw se;
16 
17 }

 

这样上级在捕获到这个异常之后,如果它想获取原始异常信息只需要 Throwable e = se.getCause()就可以了。

 

需要注意的是当存在finally并且 try中进行了return操作时,finally还会执行。

 

 

public static void f(int n) {

  try {

    int r = n * n;

    return r;

  } finally {

    //code in here

    if(n == 2) return 0;

  }

}

 

函数在返回前会执行finally中的代码,并且当n=2时,由于finally中也返回值,因此finally中的值将r覆盖,返回0。

还有一个值得注意的地方就是,当父类中的方法没有抛出异常时,子类重写父类的方法也不能抛出异常。

当父类中的方法抛出异常时,子类中重写的方法也可以抛出异常,但是子类中抛出的异常不能比父类抛出的更通用。实例如下:

public int testException() {  //父类方法}

public int testException() throws Exception{  //子类方法,报错}

public int testException() throws IOException {  //父类方法}  

public int testException() throws Exception {  //子类方法,报错。}

 

posted on 2016-07-17 22:17  terminator-LLH  阅读(437)  评论(0)    收藏  举报

导航