INF1563 Programmation I


Traitement des exceptions


Voir aussi :



Introduction

Traitement d'erreurs en Java

Traitement d'exceptions

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
}

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

Exercice

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);
    }
  }
}
  1. 10
  2. 20
  3. 30
  4. 40


Les exceptions de la classe RuntimeException

Définition de nouveaux types d'exceptions

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

Une mauvaise pratique
try {
  ...
}
catch (Exception e) {
}

le bloc "finally"