Java 示例 - 链式异常

  • 问题描述

    如何使用 catch 处理链式异常?
  • 解决方案

    此示例显示如何使用多个 catch 块处理链式异常。
    
    public class Main{
       public static void main (String args[])throws Exception { 
          int n = 20, result = 0;
          try { 
             result = n/0;
             System.out.println("The result is "+result);
          } catch(ArithmeticException ex) { 
             System.out.println ("Arithmetic exception occoured: "+ex);
             try { 
                throw new NumberFormatException();
             } catch(NumberFormatException ex1) {
                System.out.println ("Chained exception thrown manually : "+ex1);
             }
          }
       }
    }
    
  • 结果

    上面的代码示例将产生以下结果。
    
    Arithmetic exception occoured : 
    java.lang.ArithmeticException: / by zero
    Chained exception thrown manually : 
    java.lang.NumberFormatException
    
    下面是Java中使用catch处理链式异常的另一个例子
    
    public class Main{
       public static void main (String args[])throws Exception  {
          int n = 20,result = 0;
          try{
             result = n/0;
             System.out.println("The result is"+result);
          }catch(ArithmeticException ex){
             System.out.println("Arithmetic exception occoured: "+ex);
             try{  
                int data = 50/0;  
             }catch(ArithmeticException e){System.out.println(e);}  
                System.out.println("rest of the code...");  
          }
       }
    }
    
    上面的代码示例将产生以下结果。
    
    Arithmetic exception occoured: java.lang.ArithmeticException: / by zero
    java.lang.ArithmeticException: / by zero
    rest of the code...