La présentation est en train de télécharger. S'il vous plaît, attendez

La présentation est en train de télécharger. S'il vous plaît, attendez

Chapitre 11 Exceptions.

Présentations similaires


Présentation au sujet: "Chapitre 11 Exceptions."— Transcription de la présentation:

1 Chapitre 11 Exceptions

2 Sommaire Introduction Gestion d’exception Bloc try-catch
Hiérarchie des classes d’exception I/O exception INF Introduction à la programmation objet (Automne 2017) - M. Badri

3 Introduction Une exception est un objet décrivant une situation erronée ou inhabituelle Comme situation erronée, on peut citer par exemple: des données incorrectes ou fin de fichier prématurée Ces situations peuvent arriver à n’importe quel moment de l’exécution du programme. Le développeur, en plus de sa tâche principale, peut examiner toutes les situations et prendre des décisions Il peut également en oublier, ce qui rend la tâche difficile et le code complexe et illisible Pour y remédier, Java dispose d’un mécanisme appelé gestion d’exception Les exceptions sont déclenchées par une partie du programme et peuvent être traitée par une autre partie du programme Ainsi, le programme peut comporter deux types de flots : flot d’exécution normal et flot exécution d’exception INF Introduction à la programmation objet (Automne 2017) - M. Badri

4 Gestion d’exception L’API Java dispose d’un ensemble prédéfini d’exceptions pouvant survenir durant l’exécution d’un programme Face aux exceptions, le programme peut: L’ignorer – dans ce cas, le programme prend fin et affiche un message La gérer la où elle a lieu La gérer dans une autre section du programme INF Introduction à la programmation objet (Automne 2017) - M. Badri

5 //********************************************************************
// Zero.java Author: Lewis/Loftus // // Demonstrates an uncaught exception. public class Zero { // // Deliberately divides by zero to produce an exception. public static void main(String[] args) int numerator = 10; int denominator = 0; System.out.println(numerator / denominator); System.out.println("This text will not be printed."); } Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

6 Output (when program terminates)
Exception in thread "main" java.lang.ArithmeticException: / by zero at Zero.main(Zero.java:17) //******************************************************************** // Zero.java Author: Lewis/Loftus // // Demonstrates an uncaught exception. public class Zero { // // Deliberately divides by zero to produce an exception. public static void main(String[] args) int numerator = 10; int denominator = 0; System.out.println(numerator / denominator); System.out.println("This text will not be printed."); } Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

7 Bloc try-catch Pour gérer les exceptions, il faut inclure dans le bloc try les instructions susceptibles de déclencher une exception Ce bloc est suivi par la définition de un ou plusieurs gestionnaires d’exception Chaque définition de gestionnaire est précédée par le mot clé catch Chaque gestionnaire est associé à un type d’exception Lorsqu’une exception a lieu au sein d’un bloc try, le contrôle passe directement au premier catch qui correspond au type de l’exception – branchement inconditionnel au gestionnaire L’exécution se poursuit alors avec les instructions suivant ce gestionnaire Try { //instructions} Catch (..) { …….} INF Introduction à la programmation objet (Automne 2017) - M. Badri

8 Bloc try-catch - finally
Le bloc finally vient à la suite du bloc try Les instructions faisant partie du bloc finally sont toujours exécutées Ces instructions seront exécutées soit : après la fin naturelle du bloc try ou bien, après le gestionnaire d’exception (à condition que ce dernier n’ait pas provoqué l’arrêt du programme) INF Introduction à la programmation objet (Automne 2017) - M. Badri

9 Bloc try-catch – Cheminement d’exception
Pour des raisons appropriées, il arrive que dans certains cas une exception ne soit pas gérée là où elle est déclenchée On parle de cheminement d’exception, c.à.d qu’une exception peut remonter d’une méthode à une autre – voir exemple INF Introduction à la programmation objet (Automne 2017) - M. Badri

10 //********************************************************************
// Propagation.java Author: Lewis/Loftus // // Demonstrates exception propagation. public class Propagation { // // Invokes the level1 method to begin the exception demonstration. static public void main(String[] args) ExceptionScope demo = new ExceptionScope(); System.out.println("Program beginning."); demo.level1(); System.out.println("Program ending."); } Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

11 //********************************************************************
// Propagation.java Author: Lewis/Loftus // // Demonstrates exception propagation. public class Propagation { // // Invokes the level1 method to begin the exception demonstration. static public void main(String[] args) ExceptionScope demo = new ExceptionScope(); System.out.println("Program beginning."); demo.level1(); System.out.println("Program ending."); } Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

12 Output Program beginning. Level 1 beginning. Level 2 beginning.
The exception message is: / by zero The call stack trace: java.lang.ArithmeticException: / by zero at ExceptionScope.level3(ExceptionScope.java:54) at ExceptionScope.level2(ExceptionScope.java:41) at ExceptionScope.level1(ExceptionScope.java:18) at Propagation.main(Propagation.java:17) Level 1 ending. Program ending. Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

13 //********************************************************************
// ExceptionScope.java Author: Lewis/Loftus // // Demonstrates exception propagation. public class ExceptionScope { // // Catches and handles the exception that is thrown in level3. public void level1() System.out.println("Level 1 beginning."); try level2(); } catch (ArithmeticException problem) System.out.println(); System.out.println("The exception message is: " + problem.getMessage()); continue Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

14 System.out.println("The call stack trace:");
continue System.out.println("The call stack trace:"); problem.printStackTrace(); System.out.println(); } System.out.println("Level 1 ending."); // // Serves as an intermediate level. The exception propagates // through this method back to level1. public void level2() { System.out.println("Level 2 beginning."); level3(); System.out.println("Level 2 ending."); Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

15 Hiérarchie des classes d’exception
L’API Java dispose d’une hiérarchie de classes d’exception Toutes les classes d’erreur et classes d’exception sont des descendants de la classe Throwable Pour définir une exception, il faut étendre (extends) la classe d’Exception ou l’un de ses descendants en fonction de l’usage de l’exception en question INF Introduction à la programmation objet (Automne 2017) - M. Badri

16 The Exception Class Hierarchy
Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

17 //********************************************************************
// CreatingExceptions.java Author: Lewis/Loftus // // Demonstrates the ability to define an exception via inheritance. import java.util.Scanner; public class CreatingExceptions { // // Creates an exception object and possibly throws it. public static void main(String[] args) throws OutOfRangeException final int MIN = 25, MAX = 40; Scanner scan = new Scanner(System.in); OutOfRangeException problem = new OutOfRangeException("Input value is out of range."); continue Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

18 System.out.print("Enter an integer value between " + MIN +
continue System.out.print("Enter an integer value between " + MIN + " and " + MAX + ", inclusive: "); int value = scan.nextInt(); // Determine if the exception should be thrown if (value < MIN || value > MAX) throw problem; System.out.println("End of main method."); // may never reach } Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

19 Sample Run Enter an integer value between 25 and 40, inclusive: 69
Exception in thread "main" OutOfRangeException: Input value is out of range. at CreatingExceptions.main(CreatingExceptions.java:20) continue System.out.print("Enter an integer value between " + MIN + " and " + MAX + ", inclusive: "); int value = scan.nextInt(); // Determine if the exception should be thrown if (value < MIN || value > MAX) throw problem; System.out.println("End of main method."); // may never reach } Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

20 //********************************************************************
// OutOfRangeException.java Author: Lewis/Loftus // // Represents an exceptional condition in which a value is out of // some particular range. public class OutOfRangeException extends Exception { // // Sets up the exception object with a particular message. OutOfRangeException(String message) super(message); } Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

21 Hiérarchie des classes d’exception
Une exception peut être contrôlée ou non Une exception contrôlée doit être déclenchée à l’aide de la clause throws associée à la méthode qui la déclenche ou qui la propage La clause throws apparait au niveau de l’entête de la méthode A cette clause, on associe un objet dont le type servira à identifier l’exception concernée Le compilateur générera une erreur si l’exception contrôlée n’est pas captée ou listée dans la clause Throws Les exceptions non contrôlées ne nécessitent pas de gestion explicite - ex: Les objets de type RuntimeException et descendants INF Introduction à la programmation objet (Automne 2017) - M. Badri

22 I/O exception Plusieurs opérations d’entrée/sortie peuvent déclencher des exceptions du types IOException – lecture à partir d’un fichier non existant La classe IOException est une super-classe dont dérivent plusieurs sous classes représentant les problèmes pouvant survenir lors des opérations d’E/S INF Introduction à la programmation objet (Automne 2017) - M. Badri

23 //********************************************************************
// TestData.java Author: Lewis/Loftus // // Demonstrates I/O exceptions and the use of a character file // output stream. import java.util.Random; import java.io.*; public class TestData { // // Creates a file of test data that consists of ten lines each // containing ten integer values in the range 10 to 99. public static void main(String[] args) throws IOException final int MAX = 10; int value; String fileName = "test.txt"; PrintWriter outFile = new PrintWriter(fileName); continue Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

24 Random rand = new Random(); for (int line = 1; line <= MAX; line++)
continue Random rand = new Random(); for (int line = 1; line <= MAX; line++) { for (int num = 1; num <= MAX; num++) value = rand.nextInt(90) + 10; outFile.print(value + " "); } outFile.println(); outFile.close(); System.out.println("Output file has been created: " + fileName); Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

25 Random rand = new Random(); for (int line = 1; line <= MAX; line++)
continue Random rand = new Random(); for (int line = 1; line <= MAX; line++) { for (int num = 1; num <= MAX; num++) value = rand.nextInt(90) + 10; outFile.print(value + " "); } outFile.println(); outFile.close(); System.out.println("Output file has been created: " + fileName); Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri

26 Output Sample test.txt File Output file has been created: test.txt
Copyright © 2017 Pearson Education, Inc. INF Introduction à la programmation objet (Automne 2017) - M. Badri


Télécharger ppt "Chapitre 11 Exceptions."

Présentations similaires


Annonces Google