Java中自定义异常

来源:互联网 发布:seo英语编辑 编辑:程序博客网 时间:2024/06/05 16:04
java] view plain copy
 print?
  1. /*下面做了归纳总结,欢迎批评指正*/  
  2.   
  3. /*自定义异常*/  
  4. class ChushulingException extends Exception  
  5. {  
  6.     public ChushulingException(String msg)  
  7.     {  
  8.         super(msg);  
  9.     }  
  10. }   
  11.   
  12. class ChushufuException extends Exception  
  13. {  
  14.     public ChushufuException(String msg)  
  15.     {  
  16.         super(msg);  
  17.     }  
  18. }  
  19.   
  20. /*自定义异常 End*/  
  21.   
  22. class Numbertest   
  23. {  
  24.     public int shang(int x,int y) throws ChushulingException,ChushufuException  
  25.     {  
  26.         if(y<0)  
  27.         {  
  28.             throw new ChushufuException("您输入的是"+y+",规定除数不能为负数!");//抛出异常  
  29.         }  
  30.         if(y==0)  
  31.         {  
  32.             throw new ChushulingException("您输入的是"+y+",除数不能为0!");  
  33.         }  
  34.       
  35.         int m=x/y;  
  36.         return m;  
  37.     }  
  38. }  
  39.   
  40.   
  41.   
  42.   
  43.   
  44. class Rt001  
  45. {  
  46.     public static void main(String[]args)  
  47.     {  
  48.         Numbertest n=new Numbertest();  
  49.   
  50.         //捕获异常  
  51.         try  
  52.         {  
  53.             System.out.println("商="+n.shang(1,-3));  
  54.         }  
  55.         catch(ChushulingException yc)  
  56.         {  
  57.             System.out.println(yc.getMessage());  
  58.             yc.printStackTrace();  
  59.         }  
  60.         catch(ChushufuException yx)  
  61.         {  
  62.             System.out.println(yx.getMessage());  
  63.             yx.printStackTrace();  
  64.         }  
  65.         catch(Exception y)  
  66.         {  
  67.             System.out.println(y.getMessage());  
  68.             y.printStackTrace();  
  69.         }  
  70.       
  71.     finally{ System.out.println("finally!");} ////finally不管发没发生异常都会被执行    
  72.   
  73.     }  
  74. }  
  75. /* 
  76. [总结] 
  77.  
  78. 1.自定义异常: 
  79.  
  80. class 异常类名 extends Exception 
  81. { 
  82.     public 异常类名(String msg) 
  83.     { 
  84.         super(msg); 
  85.     } 
  86.  
  87.  
  88. 2.标识可能抛出的异常: 
  89.  
  90. throws 异常类名1,异常类名2 
  91.  
  92. 3.捕获异常: 
  93. try{} 
  94. catch(异常类名 y){} 
  95. catch(异常类名 y){} 
  96.  
  97. 4.方法解释 
  98. getMessage() //输出异常的信息 
  99. printStackTrace() //输出导致异常更为详细的信息 
  100.  
  101.  
  102. */  
原创粉丝点击