Java 实例 - 多个异常处理(多个catch)


对异常的处理:

1,声明异常时,建议声明更为具体的异常,这样可以处理的更具体

2,对方声明几个异常,就对应几个catch块, 如果多个catch块中的异常出现继承关系,父类异常catch块放在最下面

以下实例演示了如何处理多异常:

  1. /*
  2. author by shouce.ren
  3. ExceptionDemo.java
  4. */
  5.  
  6. class Demo
  7. {
  8. int div(int a,int b) throws ArithmeticException,ArrayIndexOutOfBoundsException//在功能上通过throws的关键字声明该功能可能出现问题
  9. {
  10. int []arr = new int [a];
  11. System.out.println(arr[4]);//制造的第一处异常
  12. return a/b;//制造的第二处异常
  13. }
  14. }
  15. class ExceptionDemo
  16. {
  17. public static void main(String[]args) //throws Exception
  18. {
  19. Demo d = new Demo();
  20. try
  21. {
  22. int x = d.div(4,0);//程序运行截图中的三组示例 分别对应此处的三行代码
  23. //int x = d.div(5,0);
  24. //int x = d.div(4,1);
  25. System.out.println("x="+x);
  26. }
  27. catch (ArithmeticException e)
  28. {
  29. System.out.println(e.toString());
  30. }
  31. catch (ArrayIndexOutOfBoundsException e)
  32. {
  33. System.out.println(e.toString());
  34. }
  35. catch (Exception e)//父类 写在此处是为了捕捉其他没预料到的异常 只能写在子类异常的代码后面
  36. //不过一般情况下是不写的
  37. {
  38. System.out.println(e.toString());
  39. }
  40. System.out.println("Over");
  41. }
  42. }

以上代码运行输出结果为:

  1. java.lang.ArrayIndexOutOfBoundsException: 4
  2. Over