如何使用 finally 塊捕獲 Java 中的異常



問題說明

如何使用 finally 塊來捕獲異常?

解決方案

本示例演示如何使用 finally 塊透過使用 e.getMessage() 來捕獲執行時異常(非法引數異常)。

public class ExceptionDemo2 {
   public static void main(String[] argv) {
      new ExceptionDemo2().doTheWork();
   }
   public void doTheWork() {
      Object o = null; 
      for (int i = 0; i < 5; i++) {
         try {
            o = makeObj(i);
         } catch (IllegalArgumentException e) {
            System.err.println("Error: ("+ e.getMessage()+").");
            return;   
         } finally {
            System.err.println("All done");
            if (o == null)
            System.exit(0);
         }
         System.out.println(o); 
      }
   }
   public Object makeObj(int type) throws IllegalArgumentException {
      if (type == 1)throw new IllegalArgumentException("Don't like type " + type);
      return new Object();
   }
}

結果

上述程式碼示例將產生以下結果。

All done
java.lang.Object@1b90b39
Error: (Don't like type 1).
All done

以下是 java 中 finally 塊的另一個示例

public class HelloWorld { 
   public static void main(String []args) { 
      try { 
         int data = 25/5; 
         System.out.println(data);
      } catch(NullPointerException e) { 
         System.out.println(e);
      } finally { 
         System.out.println("finally block is always executed"); 
      } 
      System.out.println("rest of the code...");
   }
}

上述程式碼示例將產生以下結果。

5
finally block is always executed
rest of the code...  
java_exceptions.htm
廣告
© . All rights reserved.