throws
Оновлено: 22.05.2023
❮ Ключові слова Java
Згенерувати виключення, якщо вік менше 18 років (вивести "Access denied"). Якщо вік 18 або більше, виведіть "Access granted":
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
is followed by an object (new type)- used inside the method
throws
is followed by a class- and used with the method signature
Пов'язані сторінки
Дізнайтеся більше про виключення у нашому підручнику з Java Try..Catch.
❮ Ключові слова Java