Une Error ou une Exception est un Throwable : un "lançable" contenant un message/information sur le
problème survenu. La méthode getMessage() fournit cette information.
L'exécution ne suit plus le cours normal des instructions de contrôle : if, for, ….
Le message lancé "va directement à la fin de la méthode actuelle" ou est capturé par un try-catch. Non
capturé, il agit de même avec les méthodes appelantes jusqu'au .. main : l'exception est dite "propagée".
L'exception ArithmeticException est ici traitée/capturée via le blocs try/catch "essayer/attraper". Dès
l'exception lancée, elle va exécuter le bloc catch lui correspondant.
Les Exceptions (3/8)
public class Equation2 {
public static void main(String args[]) {
...
try {
Integer x = resoudreEquation(a,b);
System.out.println("résultat équation entière ax+b=0 : X = "+x);
} catch (ArithmeticException ae) {
System.err.println("équation entière ax+b=0 : erreur d\'éxécution : "
+ ae.getMessage());
}
}
private static Integer resoudreEquation(int a, int b) {
int sol = calculSolution(a,b);
return new Integer(sol);
}
private static int calculSolution(int a, int b) {
return b/a;
}
}
Equation2.java
$ java Equation2 0 4
équation entière ax+b=0 : erreur d'éxécution : / by zero
Try Catch