Exception.
Attraper une exception.
Voici le modèle :
try {
...
Instruction1; // instruction qui lance l'exception
...
}
catch(TypeDUneException exc {
Instruction2;
...
}
Exemple :
Code exemple :
public class Attrape {
public static int moyenne(String[] liste) {
int somme = 0, nbEntiers = 0;
for (String chaine : liste) {
try {
somme += Integer.parseInt(chaine);
nbEntiers++;
}
catch (NumberFormatException e) {
System.out.println(chaine + " n'est pas entier");
}
}
return somme/nbEntiers;
}
}
Avec pour appel :
class EssaiAttrape {
public static void main(String[] arg) {
System.out. println("La moyenne est " + Attrape.moyenne("toto 12 18 14 9 titi 15));
}
}





