Voir aussi :
une erreur corrigible = un signal indiquant qu'une situation anormale a eu lieu
exemples : division par zéro, une erreur syntaxique dans un programme, une mauvaise commande dans un système d'exploitation, l'absence d'un fichier, mémoire insuffisante
java.lang.Error
java.lang.Exception
Techniquement, les exceptions sont traitées à l'aide de la construction
try { instructions } catch (class d'exception e) { instructions } ... catch (class d'exception e) { instructions }
try { .. }
détermine une séquence d'instructions susceptibles
de déclencher une exceptioncatch (class d'exception e) { ... }
attrappe les exceptions de type
indiqué et exécute les actions nécessaires pour traiter la situation qui a déclenché
l'exception attrapée
try
qui la suivent ne sont pas exécutéescatch
son exécutéescatch
Exemple (version 1) :
But : calculer le double des valeurs entières passées sur la ligne de commande.
public class Exemple { public static void main(String args[]) { for (int i=0; i<args.length; i++){ System.out.println(Integer.parseInt(args[i]) * 2); } } }
java Exemple 12 45 3a 78
Exception in thread "main" java.lang.NumberFormatException: For input string: "3a" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:458) at java.lang.Integer.parseInt(Integer.java:499) at Exemple.main(Exemple.java:7) 24 90
Exemple (version 2) :
public class Exemple { public static void main(String args[]) { try { for (int i=0; i<args.length; i++){ System.out.println(Integer.parseInt(args[i]) * 2); } } catch (NumberFormatException e){ System.out.println(1); } } }
java Exemple 12 45 3a 78
24 90 1
Quelle valeur sera affichée par le programme suivant ?
public class Quiz { public static void main(String args[]) { try { int i = 0; System.out.println(5/i); System.out.println(10); } catch (NumberFormatException e){ System.out.println(20); } catch (ArithmeticException e){ System.out.println(30); } catch (Exception e){ System.out.println(40); } } }
throws
toute sous-classe de RuntimeException qui pourrait être déclenchée durant l'exécution de la méthode mais ne pas être attrapéethrow
,
on crée une instance de cette nouvelle classethrows x
à la fin de sa signature
Exemple :
class NoteException extends Exception { public String toString() { return("Une note trop basse !\n"); } }
Exemple :
public class NoteException extends Exception { int noChapitre; public String toString() { return("Une note trop basse pour le quiz " + noChapitre + " !\n"); } } public class Quiz { int note; ... } public class Cours { static Quiz q[] = new Quiz[10]; void verifierQuiz() throws NoteException { for (int i=0; i<q.length; i++){ if (q[i].note < 1) throw new NoteException(); else System.out.println("la note pour le quiz " + i + " est " + q[i].note); } } void reprendreChapitre(int no){ ... } public static void main(String args[]) { Cours inf1563 = new Cours(); ... try { inf1563.verifierQuiz(); } catch (NoteException e){ System.out.println(e.toString()); inf1563.reprendreChapitre(e.noChapitre); } } }
Remarque : Toute méthode susceptible de déclencher une exception n'étant pas une sous-classe de RuntimeException doit
throws
try { ... } catch (Exception e) { }
catch
sont suivies optionnellement par
un bloc finally
... try { // ouvrir un fichier et effectuer certains traitements // susceptibles de déclencher l'exception IOException } catch (IOException e) { // traiter l'exception } catch (Exception e){ // traiter d'autres exceptions si c'est le cas } finally { //fermer le fichier }
finally
contient du code qui sera exécuté quelle que soit
la manière dont le bloc try a été quittétry
s'est exécuté normalement sans aucune
exception déclenchéetry
déclenche une exception attrapée par
l'un des blocs catch
try
déclenche une exception qui n'est
attrapée par aucun des blocs catch
qui le suivent