Parola chiave di lancio di Java

❮ Parole chiave Java


Esempio

Genera un'eccezione se l' età è inferiore a 18 (stampa "Accesso negato"). Se l'età ha 18 anni, stampa "Accesso concesso":

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...)
  }
}


Definizione e utilizzo

La throwparola chiave viene utilizzata per creare un errore personalizzato.

L' throwistruzione viene utilizzata insieme a un tipo di eccezione . Ci sono molti tipi di eccezioni disponibili in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, ecc.

Il tipo di eccezione viene spesso utilizzato insieme a un metodo personalizzato , come nell'esempio precedente.

Differenze tra throwe 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:
  • 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

Pagine correlate

Leggi di più sulle eccezioni nel nostro tutorial Java Try..Catch .


❮ Parole chiave Java