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不管发没发生异常都会被执行    
      
        }  
    } 
    


  • 相关阅读:
    一些java的基础知识
    android基础AlertDialog使用
    Js+XML 操作 [ZT]
    [ASP.NET2.0] asp.net在ie7中使用FileUpload上传前预览图片 [ZT]
    C#对图片的几种简单处理 [ZT]
    使用 Bulk Copy 将大量数据复制到数据库 [ZT]
    html中name和id的区别 [ZT]
    两个分页存储过程
    C#常用的文件操作 (转)
    JSON
  • 原文地址:https://www.cnblogs.com/riasky/p/3478523.html
Copyright © 2011-2022 走看看