Java | throws
Le mot clé throws indique quel type d’exception peut être levé par une méthode.
Il existe différents types d’exceptions disponibles en Java: ArithmeticException, NullPointerException, ClassNotFoundException, SecurityException, etc.
Syntaxe:
return_type method_name() throws exception_type{
//code
}
Exemple:
Lever une exception si le nombre est négatif et affichez « Erreur : Nombre négatif. ». Si le nombre est positif affichez « OK : Nombre positif »:
public class Main {
static void check(int nbr) throws ArithmeticException {
if (nbr < 0) {
throw new ArithmeticException("Erreur : Nombre négatif.");
}
else {
System.out.println("OK : Nombre positif");
}
}
public static void main(String[] args) {
check(-10);
}
}
Sortie:
Exception in thread "main" java.lang.ArithmeticException: Erreur : Nombre négatif. at Main.check(Main.java:5) at Main.main(Main.java:13)





