Java中自定义异常

时间:2023-03-09 19:31:37
Java中自定义异常
  1. /*下面做了归纳总结,欢迎批评指正*/
  2. /*自定义异常*/
  3. class ChushulingException extends Exception
  4. {
  5. public ChushulingException(String msg)
  6. {
  7. super(msg);
  8. }
  9. }
  10. class ChushufuException extends Exception
  11. {
  12. public ChushufuException(String msg)
  13. {
  14. super(msg);
  15. }
  16. }
  17. /*自定义异常 End*/
  18. class Numbertest
  19. {
  20. public int shang(int x,int y) throws ChushulingException,ChushufuException
  21. {
  22. if(y<0)
  23. {
  24. throw new ChushufuException("您输入的是"+y+",规定除数不能为负数!");//抛出异常
  25. }
  26. if(y==0)
  27. {
  28. throw new ChushulingException("您输入的是"+y+",除数不能为0!");
  29. }
  30. int m=x/y;
  31. return m;
  32. }
  33. }
  34. class Rt001
  35. {
  36. public static void main(String[]args)
  37. {
  38. Numbertest n=new Numbertest();
  39. //捕获异常
  40. try
  41. {
  42. System.out.println("商="+n.shang(1,-3));
  43. }
  44. catch(ChushulingException yc)
  45. {
  46. System.out.println(yc.getMessage());
  47. yc.printStackTrace();
  48. }
  49. catch(ChushufuException yx)
  50. {
  51. System.out.println(yx.getMessage());
  52. yx.printStackTrace();
  53. }
  54. catch(Exception y)
  55. {
  56. System.out.println(y.getMessage());
  57. y.printStackTrace();
  58. }
  59. finally{ System.out.println("finally!");} ////finally不管发没发生异常都会被执行
  60. }
  61. }
  62. /*
  63. [总结]
  64. 1.自定义异常:
  65. class 异常类名 extends Exception
  66. {
  67. public 异常类名(String msg)
  68. {
  69. super(msg);
  70. }
  71. }
  72. 2.标识可能抛出的异常:
  73. throws 异常类名1,异常类名2
  74. 3.捕获异常:
  75. try{}
  76. catch(异常类名 y){}
  77. catch(异常类名 y){}
  78. 4.方法解释
  79. getMessage() //输出异常的信息
  80. printStackTrace() //输出导致异常更为详细的信息
  81. */

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