×
例外処理
throw による例外の意図的発生と、throws による呼び出し元への例外委譲のコード例です。
import java.io.IOException;

public class ThrowThrowsExample {
    // throws: 例外が発生する可能性を呼び出し元へ通知
    public static void checkAge(int age) throws IOException {
        if (age < 0) {
            // throw: 新しい例外オブジェクトを意図的に発生させる
            throw new IOException("年齢は0以上でなければなりません。");
        }
    }

    public static void main(String[] args) {
        try {
            checkAge(-5);
        } catch (IOException e) {
            System.out.println("捕捉: " + e.getMessage());
        }
    }
}

もう少し詳しく