スロー

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

Jim White

Java Developer

処理の選択肢

  • チェック例外は「処理」が必須
    • 実行時例外の「処理」は任意
  • 「処理」の選択肢は2つ
    • try/catch で Exception を捕捉し対処コードを書く
    • 例外を「throw」する
  • 例外処理は try/catch が推奨
    • ただし常に可能ではなく、処理の集約が有利な場合もある
Javaにおけるデータ型と例外処理

throws キーワード

  • throws を付けると、例外を呼び出し元へ渡せます
    • メソッド内で処理する代わり
    • これを「例外をスロー(丸投げ)」と呼ぶことがあります
    • 例外処理の責任を呼び出し側へ移譲
  • throws の後に例外型をカンマ区切りで列挙
    • 呼び出し側が想定すべき例外型を示す
public static void someMethod() throws IndexOutOfBoundsException, 
NegativeArraySizeException, NullPointerException {
  // method code
}
Javaにおけるデータ型と例外処理
throws の例

通常の try-catch で Exception を処理

public static void main(String[] args) {
  someMethod();
}
public static void someMethod(){
  try {
    ArrayList<String> games
      = new ArrayList<String>();
    games.add("Monopoly");
    games.add("Chess");
    games.get(3);
  } catch (IndexOutOfBoundsException e) {
    System.out.println(
   "Oops - trying to get non-existent item");
  }
}

throws で Exception を処理

public static void main(String[] args) {
  try {
    someMethod();
  } catch (IndexOutOfBoundsException e) {
    System.out.println(
   "someMethod tried to get non-existent item");
  }
}
public static void someMethod()
      throws IndexOutOfBoundsException {
  ArrayList<String> games
    = new ArrayList<String>();
  games.add("Monopoly");
  games.add("Chess");
  games.get(3);
}
Javaにおけるデータ型と例外処理

throws を使う場面

  • 「丸投げ」= 例外をスローするのは、基本的に避けます
    • 通常は発生箇所で try-catch するのが望ましい
  • それでも throws を使う理由:
    • 発生元メソッドでは復旧方法が不明な場合
    • 処理を集中させ、冗長な try/catch を減らすため

例外スローは主にカスタム例外で用いられる

1 Photo from https://unsplash.com/@philipparosetite
Javaにおけるデータ型と例外処理

キャッチして再スロー

  • Exception は「再スロー」できます
    • 呼び出し元のメソッドが try/catch せずに throws を使う
  • main から再スローするとアプリが停止します

例外は呼び出し元へ再スローできる

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

再スローの例

public class RethrowExample {
    public static void main(String[] args) {
        try {
            method1(0);
        } catch (ArithmeticException e) {
            System.out.println("Oops - tried a bad quotient");
        }
    }
    public static void method1(int divisor) throws ArithmeticException {
        method2(divisor);
    }
    public static void method2 (int divisor) throws ArithmeticException {
        int z = 5/divisor;
        System.out.println(z);
    }
}
Javaにおけるデータ型と例外処理

Let's practice!

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

Preparing Video For Download...