Java 實例 - 鏈試異常

Java 實例 Java 實例

以下實例演示了使用多個 catch 來處理鏈試異常:

Main.java 檔

public class Main { public static void main (String args[])throws Exception { int n=20,result=0; try{ result=n/0; System.out.println("結果為"+result); } catch(ArithmeticException ex){ System.out.println("發算術異常: "+ex); try { throw new NumberFormatException(); } catch(NumberFormatException ex1) { System.out.println("手動拋出鏈試異常 : "+ex1); } } } }

以上代碼運行輸出結果為:

發算術異常: java.lang.ArithmeticException: / by zero
手動拋出鏈試異常 : java.lang.NumberFormatException

Java 實例 Java 實例