zoukankan      html  css  js  c++  java
  • java 如何自定义异常 用代码展示 真心靠谱

    先建两个自定义的异常类


    ChushufuException类

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


    ChushulingException


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




    好了,然后再写一个测试类Numbertest


    class Numbertest   
    {  
        public int shang(int x,int y) throws ChushulingException,ChushufuException  
        {  
            if(y<0)  
            {  
                throw new ChushufuException("xxxxxxxxxxx您输入的是"+y+",规定除数不能为负数!");//抛出异常  
            }  
            if(y==0)  
            {  
                throw new ChushulingException("您输入的是"+y+",除数不能为0!");  
            }  
          
            int m=x/y;  
            return m;  
        }  
    }


    是不是很简洁明了?


    再来一个测试类


    class Rt001  
    {  
        public static void main(String[]args) throws ChushulingException  
        {  
            Numbertest n=new Numbertest();  
        	Logger logger = Logger.getLogger(Rt001.class.getName());
            //捕获异常  
            try  
            {  
                System.out.println("商="+n.shang(1,-3));  
            }  
    //        catch(ChushulingException yc)  
    //        {  
    //            System.out.println(yc.getMessage());  
    //            yc.printStackTrace();  
    //        }  
            catch(ChushufuException yx)  
            {  
                System.out.println(yx.getMessage());  
                yx.printStackTrace();  
                logger.error("oops, got an exception: ",yx);
            }  
    //        catch(Exception y)  
    //        {  
    //            System.out.println(y.getMessage());  
    //            y.printStackTrace();  
    //        }  
          
        //finally{ System.out.println("finally!");} ////finally不管发没发生异常都会被执行    
      
        }  
    } 
    


  • 相关阅读:
    SpringBoot多数据源:动态数据源
    cron 表达式
    6种@Transactional注解的失效场景
    spring boot 整合mybatis 的xml版本
    MySQL函数大全 及用法示例
    后端必备 Nginx 配置
    详解SpringBoot应用跨域访问解决方案
    Lombok使用
    前端必备 Nginx 配置
    随便写写插入排序
  • 原文地址:https://www.cnblogs.com/riasky/p/3478523.html
Copyright © 2011-2022 走看看