try と catch

Javaにおけるデータ型と例外処理

Jim White

Java Developer

Java の問題

  • アプリでは問題が起こり得る
    • 誤入力
    • コーディングミス
    • 想定外の事象
  • これらの問題は「例外」と呼ぶ
    • 通常の制御フローを中断
  • Java は例外を「スロー」する
Javaにおけるデータ型と例外処理

例外の例

public static void main(String[] args) {
    ArrayList<String> allStars = new ArrayList<String>();
    allStars.add("Mays");
    allStars.add("Aaron");
    allStars.add("Ruth");
    String last = allStars.get(3); // This will cause an exception
    System.out.println(last);
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of 
bounds for length 3
Javaにおけるデータ型と例外処理

try

  • 例外が起こり得るコードを try ブロックで囲む
    • 「このコードを試し、問題があれば catch に渡す」
try {
    // 例外を監視しつつ実行する文
}
Javaにおけるデータ型と例外処理

catch

  • try の後に catch ブロックを置く
    • 例外を処理するハンドラー
    • 捕捉した例外は引数として渡される
  • 例外の種類によっては try/catch が必須
    • 任意のものもある
try {
    // 例外を監視しつつ実行する文
} catch (<Exception type> <variable name>) {
    // 例外発生時に実行する文
}
Javaにおけるデータ型と例外処理

IndexOutOfBoundsException を捕捉する

try {
  ArrayList<String> allStars = new ArrayList<String>();
  allStars.add("Mays");
  allStars.add("Aaron");
  allStars.add("Ruth");
  String last = allStars.get(3); // Accessing an element that isn't there
  System.out.println(last);
} catch (IndexOutOfBoundsException e) {
  System.out.println("Oops - wrong index");
}
Oops - wrong index
Javaにおけるデータ型と例外処理

複数の catch

  • 例外の種類ごとに複数の catch を使う
  • catch は固有の例外型と変数を持つ
  • 例外発生時、Java は上から順に catch を確認し一致を探す
try {
    ArrayList<String> nums 
      = new ArrayList<String>();
    nums.add("one");
    String last = nums.get(0);
    Integer.valueOf(last);
    System.out.println(last);
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println(
      "Oops - String not a number");
}
Oops - String not a number
Javaにおけるデータ型と例外処理

包括的な catch

  • catch (Exception 変数){ } で包括的に捕捉
    • 他の catch で処理されない例外を扱う
try {
    // Code to try
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops - String not a number");
} catch (Exception e) { // 上記以外のすべてを処理
    System.out.println("Something unplanned happened");
}
Javaにおけるデータ型と例外処理

finally

  • finally ブロックのコードは常に実行される
// 例外が発生する場合
try {
    Integer.valueOf("one");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Oops
Doing cleanup

 

// 例外が発生しない場合
try {
    Integer.valueOf("1");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Doing cleanup
Javaにおけるデータ型と例外処理

Exception オブジェクト

  • catch に渡される Exception オブジェクトには多くの情報がある
  • メソッドで原因を詳しく確認する
    • .getMessage() 人間可読な原因
    • .getClass() 例外クラス(型)名
    • .printStackTrace() スタックトレースを表示(次スライド)
public class ExceptionExample {

    public static void main(String[] args) {
        try {
            Integer.valueOf("one");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
Javaにおけるデータ型と例外処理

例外のスタックトレース

  • 「スタックトレース」は問題までの実行経路を示す記録
    • 下は前のコード例の出力(印字されたスタックトレースを含む)
For input string: "one"
java.lang.NumberFormatException: For input string: "one"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:661)
    at java.base/java.lang.Integer.valueOf(Integer.java:988)
    at foo/exceptions.ExceptionExample.main(ExceptionExample.java:7)
Javaにおけるデータ型と例外処理

練習しましょう!

Javaにおけるデータ型と例外処理

Preparing Video For Download...