Java lance un mot-clé
Exemple
Lancer une exception si l' âge est inférieur à 18 ans (imprimer "Accès refusé"). Si l'âge est de 18 ans ou plus, écrivez "Accès accordé":
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...)
}
}
Définition et utilisation
Le throws
mot-clé indique quel type d'exception peut être lancé par une méthode.
Il existe de nombreux types d'exceptions disponibles en Java : ArithmeticException
, ClassNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
, etc.
Différences entre throw
et 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:
|
Pages connexes
En savoir plus sur les exceptions dans notre Java Try..Catch Tutorial .