Java 实例 - 链试异常


以下实例演示了使用多个 catch 来处理链试异常:

  1. /*
  2. author by shouce.ren
  3. Main.java
  4. */
  5.  
  6. public class Main{
  7. public static void main (String args[])throws Exception {
  8. int n=20,result=0;
  9. try{
  10. result=n/0;
  11. System.out.println("结果为"+result);
  12. }
  13. catch(ArithmeticException ex){
  14. System.out.println("发算术异常: "+ex);
  15. try {
  16. throw new NumberFormatException();
  17. }
  18. catch(NumberFormatException ex1) {
  19. System.out.println("手动抛出链试异常 : "+ex1);
  20. }
  21. }
  22. }
  23. }

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

  1. 发算术异常: java.lang.ArithmeticException: / by zero
  2. 手动抛出链试异常 : java.lang.NumberFormatException