Javaはキーワードをスローします
例
年齢が18歳未満の場合は、例外をスローします(「アクセスが拒否されました」と印刷します)。18歳以上の場合は、「アクセス許可」と印刷してください。
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
定義と使用法
throws
キーワードは、メソッドによってスローされる可能性のある例外タイプを示します。
Javaで使用できる例外の種類はたくさんあります:ArithmeticException
、、、、ClassNotFoundException
など。ArrayIndexOutOfBoundsException
SecurityException
throw
との違いthrows
:
throw | throws |
---|---|
Used to throw an exception for a method | Used to indicate what exception type may be thrown by a method |
Cannot throw multiple exceptions | Can declare multiple exceptions |
Syntax:
|
Syntax:
|
関連ページ
例外の詳細については、JavaのTry..Catchチュートリアルを参照してください。