JavaSE 基础 第50节 Java中的异常链

2016-06-30

1 异常链
两个或多个不同的异常出现在同一个程序中,并且会发生嵌套抛出,我们称之为异常链。

package com.java1995;
/**
 * 异常链
 * @author Administrator
 *
 */
public class ExceptionChainTest {
    
    public static void main(String[] args) {
        
        Calculator c=new Calculator();
        try{
            c.chufa(1, 0);
                }catch(NumberCalculateException e){
                    e.printStackTrace();
                    System.out.println("错误原因"+e);
                };
    }

}

class Calculator{
    
    /**
     * 除法
     * @return
     * @throws NumberCalculateException 
     */
    public int chufa(int i,int j) throws NumberCalculateException{
        if(j==0){
            NumberCalculateException e=
                    new NumberCalculateException("计算错误");
            NegativeNumberException e1=
                    new NegativeNumberException("除数不能被0");
            e.initCause(e1);
            throw e;
        }
        return 0;
    };
}

class NegativeNumberException extends Exception {
    
    public NegativeNumberException(String msg){
        super(msg);
    }
}

class NumberCalculateException extends Exception {
    
    public NumberCalculateException(String msg){
        super(msg);
    }
}

 

【参考资料】

[1] Java轻松入门经典教程【完整版】

 

posted @ 2016-06-30 18:47  岑亮  阅读(147)  评论(0编辑  收藏  举报