如何使用 catch 處理 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...
java_exceptions.htm
廣告
© . All rights reserved.