throw

Оновлено: 22.05.2023

❮ Ключові слова Java

Згенерувати виключення, якщо вік менше 18 років (вивести "Access denied"). Якщо вік 18 або більше, виведіть "Access granted":

public class Main {
  static void checkAge(int age) {
    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...)
  }
}

Визначення та використання

Ключове слово throw використовується для створення користувацької помилки.

Оператор throw використовується разом з типом виключення. У мові Java існує багато типів винятків: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException тощо.

Тип виключення часто використовується разом з користувацьким методом, як у наведеному вище прикладі.

Відмінності між кидком і кидком:

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:
  • throw is followed by an object (new type)
  • used inside the method
Syntax:
  • throws is followed by a class
  • and used with the method signature

Пов'язані сторінки

Дізнайтеся більше про виключення у нашому підручнику з Java Try..Catch.

❮ Ключові слова Java