Java基础--异常--自定义异常

用于处理项目中可能会出现的特有的问题,对这些问题进行自定义的异常封装。

ExceptionTest.java

public class ExceptionTest {
    public static void main(String[] args){
        DivDemo dd = new DivDemo();
        
        int resultD;
        try {
            resultD = dd.div(10, -1);
            System.out.println("resultD' value is :"+resultD);
        }  catch (ArithmeticException e){
            System.out.println("Arithmetic异常: "+e.toString());
        }  catch (FuShuException e){
            System.out.println("FuShu异常: "+e.toString());
            System.out.println("负数为:"+e.value);
            
        }
        System.out.println("over!");
    }
}

//创建自定义异常类---继承Exception,才有了可抛性,这个可抛性是throwable体系具有的。
class FuShuException extends Exception{
int value;
    
    FuShuException(){
        super();
    }
    //异常信息message
    FuShuException(String msg,int val){
        super(msg);
        this.value = val;
    }
    
    public int getValue(){
        return this.value;
    }
}

class DivDemo{
    public int div(int a,int b) throws ArithmeticException,FuShuException{

        if(a < 0 ){
            throw new FuShuException("出现了负数",a); 
            //主动抛FuShuException异常
        }
        
        if(b < 0 ){
            throw new FuShuException("出现了负数",b);  
            //主动抛FuShuException异常
        }
        
        return a/b;   
    }
}

<console>

image

posted @ 2015-07-14 16:52  cuiz_book  阅读(229)  评论(0编辑  收藏  举报