Javaexamples-exception-finally

提供:Dev Guides
移動先:案内検索

Javaの例-finallyの使用

問題の説明

例外をキャッチするためにfinallyブロックを使用する方法は?

溶液

この例では、e.getMessage()を使用して、finallyブロックを使用してランタイム例外(無効な引数例外)をキャッチする方法を示します。

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...