Java中自定义异常

  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.     public 异常类名(String msg) 
  82.     { 
  83.         super(msg); 
  84.     } 
  85. }  
  86.  
  87. 2.标识可能抛出的异常: 
  88.  
  89. throws 异常类名1,异常类名2 
  90.  
  91. 3.捕获异常: 
  92. try{} 
  93. catch(异常类名 y){} 
  94. catch(异常类名 y){} 
  95.  
  96. 4.方法解释 
  97. getMessage() //输出异常的信息 
  98. printStackTrace() //输出导致异常更为详细的信息 
  99.  
  100.  
  101. */  

出处:http://blog.csdn.net/stellaah/article/details/6738424

原文地址:https://www.cnblogs.com/handsome1013/p/4871735.html