Try et Catch

Types de données et exceptions en Java

Jim White

Java Developer

Problèmes en Java

  • Des problèmes peuvent survenir dans les applications
    • À cause de saisies incorrectes
    • À cause d'erreurs de code
    • À cause d'imprévus
  • Ces problèmes sont des exceptions
    • Interrompent le flux normal d'exécution
  • Java lève des exceptions
Types de données et exceptions en Java

Exemple d'exception

public static void main(String[] args) {
    ArrayList<String> allStars = new ArrayList<String>();
    allStars.add("Mays");
    allStars.add("Aaron");
    allStars.add("Ruth");
    String last = allStars.get(3); // This will cause an exception
    System.out.println(last);
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of 
bounds for length 3
Types de données et exceptions en Java

Try

  • Entourez le code susceptible de générer une exception d'un bloc try
    • « Essayez ce code et, en cas de problème, passez au bloc catch »
try {
    // Instructions à exécuter et surveiller pour des exceptions
}
Types de données et exceptions en Java

Catch

  • Placez un bloc catch après le try
    • Sert de gestionnaire pour traiter l'exception
    • L'exception interceptée est passée en paramètre
  • Les blocs try/catch sont requis pour certains types d'exceptions
    • Optionnels pour d'autres
try {
    // Instructions à exécuter et surveiller pour des exceptions
} catch (<Exception type> <variable name>) {
    // Instructions à exécuter si une exception s'est produite
}
Types de données et exceptions en Java

Intercepter IndexOutOfBoundsException

try {
  ArrayList<String> allStars = new ArrayList<String>();
  allStars.add("Mays");
  allStars.add("Aaron");
  allStars.add("Ruth");
  String last = allStars.get(3); // Accessing an element that isn't there
  System.out.println(last);
} catch (IndexOutOfBoundsException e) {
  System.out.println("Oops - wrong index");
}
Oops - wrong index
Types de données et exceptions en Java

Catch multiples

  • Utilisez plusieurs blocs catch pour différents types d'exceptions
  • Chaque catch a son propre type d'exception et sa variable
  • Lorsqu'une exception survient, Java parcourt les catch dans l'ordre jusqu'au premier qui correspond
try {
    ArrayList<String> nums 
      = new ArrayList<String>();
    nums.add("one");
    String last = nums.get(0);
    Integer.valueOf(last);
    System.out.println(last);
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println(
      "Oops - String not a number");
}
Oops - String not a number
Types de données et exceptions en Java

Catch « All »

  • Utilisez catch (Exception variable){ } comme « attrape-tout »
    • Gère toute exception non traitée par les autres blocs catch
try {
    // Code à essayer
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops - String not a number");
} catch (Exception e) { // Gère toutes les exceptions sauf les deux ci-dessus
    System.out.println("Something unplanned happened");
}
Types de données et exceptions en Java

Finally

  • Le code du bloc finally s'exécute toujours
// When exception happens
try {
    Integer.valueOf("one");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Oops
Doing cleanup

 

// When no exception gets thrown
try {
    Integer.valueOf("1");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Doing cleanup
Types de données et exceptions en Java

Objet Exception

  • L'objet Exception passé au bloc catch contient beaucoup d'informations
  • Utilisez ses méthodes pour comprendre l'erreur
    • .getMessage() pour la cause lisible
    • .getClass() pour la classe/type de l'exception
    • .printStackTrace() pour afficher la trace de pile (slide suivante)
public class ExceptionExample {

    public static void main(String[] args) {
        try {
            Integer.valueOf("one");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
Types de données et exceptions en Java

Trace de pile d'une exception

  • La trace de pile retrace l'exécution jusqu'au problème
    • Ci-dessous : sortie de l'exemple précédent, incluant la trace de pile imprimée
For input string: "one"
java.lang.NumberFormatException: For input string: "one"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:661)
    at java.base/java.lang.Integer.valueOf(Integer.java:988)
    at foo/exceptions.ExceptionExample.main(ExceptionExample.java:7)
Types de données et exceptions en Java

Passons à la pratique !

Types de données et exceptions en Java

Preparing Video For Download...