Types de données et exceptions en Java
Jim White
Java Developer
Exception et coder une solutionthrows sur toute méthode pour renvoyer l'exception à l'appelantthrows les types d'exception, séparés par des virgulespublic static void someMethod() throws IndexOutOfBoundsException,
NegativeArraySizeException, NullPointerException {
// method code
}
Try-catch normal pour gérer une Exception
public static void main(String[] args) {
someMethod();
}
public static void someMethod(){
try {
ArrayList<String> games
= new ArrayList<String>();
games.add("Monopoly");
games.add("Chess");
games.get(3);
} catch (IndexOutOfBoundsException e) {
System.out.println(
"Oups – tentative d'obtenir un élément inexistant");
}
}
Throws pour gérer une Exception
public static void main(String[] args) {
try {
someMethod();
} catch (IndexOutOfBoundsException e) {
System.out.println(
"someMethod a tenté d'obtenir un élément inexistant");
}
}
public static void someMethod()
throws IndexOutOfBoundsException {
ArrayList<String> games
= new ArrayList<String>();
games.add("Monopoly");
games.add("Chess");
games.get(3);
}

Exception peut être « relancée »main arrêtera l'application
public class RethrowExample {
public static void main(String[] args) {
try {
method1(0);
} catch (ArithmeticException e) {
System.out.println("Oups – quotient invalide tenté");
}
}
public static void method1(int divisor) throws ArithmeticException {
method2(divisor);
}
public static void method2 (int divisor) throws ArithmeticException {
int z = 5/divisor;
System.out.println(z);
}
}
Types de données et exceptions en Java