Vous êtes sur la page 1sur 29

Java avancé

(Gestion des exceptions)


E.I. Djebbar
Département de Génie des systèmes
Ecole Nationale Polytechnique d’Oran

Programmation Objet Avancée (POA) 1

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Plan

• Définition
• Déroulement
• Les exceptions de type RunTimeException
• Définition et lancement d’exceptions utilisateurs (throw et throws)
• Gestion de plusieurs exceptions

Programmation Objet Avancée (POA) 2

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Définition

• Une exception est un événement exceptionnel risquant de compromettre le bon


déroulement du programme. Un débordement de tableau ou de pile, la lecture
d’une donnée erronée ou d’une fin de fichier prématurée constituent des
exemples d’exceptions.

Programmation Objet Avancée (POA) 3

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Déroulement

• En Java, la fonction peut lancer une exception en indiquant un type d’exception.


• L’exception se "propage" de retour de méthode en retour de méthode jusqu’à ce
qu’une méthode la traite.
• Si aucune méthode ne la prend en compte, il y a un message d’erreur
d’exécution.
• Suite à une exception, toutes les instructions sont ignorées, sauf les instructions
chargées de capter cette exception.

Programmation Objet Avancée (POA) 4

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Les exceptions de type RunTimeException
(1)
• Exemple1 : Les débordements de tableaux (dans main)
• L’exécution du programme ci-dessus provoque un message d’erreur indiquant une exception
du type ArrayIndexOutOfBoundsException, et l’arrêt du programme.
• Le tableau de 4 entiers tabEnt a des indices de 0 à 3. L’accès à la valeur d’indice 5 provoque
une exception non captée.

Programmation Objet Avancée (POA) 5

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Les exceptions de type RunTimeException

• Exemple1
public class TestException1 {
public static void main (String[] args) {
int tabEnt[] = { 1, 2, 3, 4 };
tabEnt [4] = 0;
System.out.println ("Fin du main");
}
}
Programmation Objet Avancée (POA) 6

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
• Dans le programme suivant, la même erreur d’accès à un élément est captée par
le programme.
• Lors de la rencontre de l’erreur, les instructions en cours sont abandonnées et un
bloc de traitement (catch) de l’exception est recherché et exécuté.
• Le traitement se poursuit après ce bloc sauf indication contraire du catch (return
ou arrêt par exemple).
• Le message "Fin du main" est écrit après interception de l’exception.
Programmation Objet Avancée (POA) 7

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Les exceptions de type RunTimeException
• Exemple2
public class TestException2 {
public static void main (String[] args) {
try {
int tabEnt[] = { 1, 2, 3, 4 };
tabEnt [4] = 0;
System.out.println ("Fin du try");
} catch (Exception e) {
System.out.println ("Exception : " + e);}
System.out.println ("Fin du main");}
}
Résultats d’exécution :
Exception : java.lang.ArrayIndexOutOfBoundsException
Fin de main
Programmation Objet Avancée (POA) 8

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Les exceptions de type RunTimeException
(2)
• Exemple2 : Null Pointer
• Les deux instructions suivantes provoquent une exception de type NullPointerException.
• s1 est une référence null sur un (futur) objet de type String.
• On ne peut pas accéder au troisième caractère de l’objet String référencé par null, d’où
l’exception.

Programmation Objet Avancée (POA) 9

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Les exceptions de type RunTimeException
(2)

•Exemple2
public class TestException3{
public static void main (String[] args) {
String s1 = null;
System.out.println (s1.charAt(3));
}}
Programmation Objet Avancée (POA) 10

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Les exceptions de type RunTimeException
• Exemple2 (2)
public class TestException4 {
public static void main (String[] args) {
try {
String s1 = null;
System.out.println (s1.charAt(3));
} catch (Exception e) {
System.out.println ("Exception : " + e);}
System.out.println ("Fin du main"); }
}
Résultats d’exécution :
Exception : java.lang.NullPointerException
Fin de main
Programmation Objet Avancée (POA) 11

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Les exceptions de type RunTimeException
(3)

• Exemple3:
• Le programme suivant donne des exemples où une exception est lancée : chaîne à convertir
en entier ne contenant pas un entier (lecture erronée d’un entier par exemple), division par
zéro, transtypage non cohérent de deux objets de classes différentes, essai d’ouverture d’un
fichier n’existant pas.

Programmation Objet Avancée (POA) 12

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Les exceptions de type RunTimeException (3)

• Exemple 3: int d = 0;
import java.awt.*; int quotient = 17 / d; // exception
public class TestException5 { de type ArithmeticException
public static void main (String[] args) { System.out.println ("quotient : " +
// convertit la chaine "231" en un entier quotient);
binaire
Object p = new Point();
int n1 = Integer.parseInt ("231");
System.out.println ("n1 : " + n1); Color coul = (Color) p; // exception
// exception NumberFormatException ci-
ClassCastException :
dessous
// p n’est pas de la classe Color
int n2 = Integer.parseInt ("231x");
System.out.println ("Fin de main");
System.out.println ("n2 : " + n2);
}

Programmation Objet Avancée (POA) 13


Définition et lancement d’exceptions
utilisateurs (throw et throws) (1)
• Exemple:
• Soit une classe Point, munie d’un constructeur à deux arguments et d’une
méthode affiche. On souhaite manipuler que des points ayant des
coordonnées non négatives.
• On peut, au sein du constructeur, vérifier la validité des paramètres fournis.
Lorsque l’un d’entre eux est incorrect, nous "déclenchons" une exception à
l’aide de l’instruction throw.

Programmation Objet Avancée (POA) 14

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Définition et lancement d’exceptions
utilisateurs (throw et throws) (1)

• Exemple (Suite):
• On doit fournir un objet dont le type servira ultérieurement à identifier
l’exception concernée.
• On crée artificiellement une classe nommée ErrCoord. Java impose que
cette classe dérive de la classe standard Exception.

Programmation Objet Avancée (POA) 15

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Définition et lancement d’exceptions
utilisateurs (throw et throws) (1)
• Création de classe qui dérive de la classe standard Exception.
• class ErrConst extends Exception{ }
• Pour lancer une exception de ce type au sein de notre constructeur, nous fournirons à
l’instruction throw un objet de type Errconst, par exemple de cette façon :
• throw new ErrConst() ;
• En définitive, le constructeur de notre classe Point peut se présenter ainsi :
class Point
{ public Point(int x, int y) throws ErrConst
{ if ( (x<0) || (y<0)) throw new ErrConst() ;
this.x = x ; this.y = y ; // type ErrConst}

Programmation Objet Avancée (POA) 16

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Définition et lancement d’exceptions
utilisateurs (throw et throws) (1)

• Exemple complet :
public class Except1
{ public static void main (String args[])
class Point { try
{ Point a = new Point (1, 4) ;
{ public Point(int x, int y) throws ErrConst
a.affiche() ;
{ if ( (x<0) || (y<0)) throw new ErrConst() ; a = new Point (-3, 5) ;
this.x = x ; this.y = y ;} a.affiche() ;
}
public void affiche()
catch (ErrConst e)
{ System.out.println ("coordonnees : " + x + " { System.out.println ("Erreur construction ");
" + y) ;} System.exit (-1) ;
private int x, y ; }
} }
}
class ErrConst extends Exception{ } coordonnees : 1 4
Erreur construction
Programmation Objet Avancée (POA) 17

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Gestion de plusieurs exceptions
• On peut déclencher et traiter deux types d’exceptions. Pour ce faire, nous
considérons une classe Point munie :
• D’un constructeur précédent, déclenchant toujours une exception ErrConst,
• d’une méthode deplace qui s’assure que le déplacement ne conduit pas à une coordonnée
négative ; si tel est le cas, elle déclenche une exception ErrDepl (on crée donc, ici encore, une
classe ErrDepl) :
• public void deplace (int dx, int dy) throws ErrDepl
• { if ( ((x+dx)<0) || ((y+dy)<0)) throw new ErrDepl() ;
• x += dx ; y += dy ;
• }

Programmation Objet Avancée (POA) 18

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Gestion de plusieurs exceptions
• Lors de l’utilisation de notre classe Point, nous pouvons détecter les deux
exceptions potentielles ErrConst et ErrDepl en procédant ainsi (ici, nous nous
contentons comme précédemment d’afficher un message et d’interrompre
l’exécution) :
try
{ // bloc dans lequel on souhaite detecter les exceptions ErrConst et ErrDepl
}
catch (ErrConst e) // gestionnaire de l’exception ErrConst
{ System.out.println ("Erreur construction ") ;
System.exit (-1) ;
}
catch (ErrDepl e) // gestionnaire de l’exception ErrDepl
{ System.out.println ("Erreur deplacement ") ;
System.exit (-1) ;
}

Programmation Objet Avancée (POA) 19

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Exemple complet
public class Except2
class Point { public static void main (String args[])
{ public Point(int x, int y) throws ErrConst { try
{ if ( (x<0) || (y<0)) throw new ErrConst() ; { Point a = new Point (1, 4) ;
this.x = x ; this.y = y ;} a.affiche() ;
public void deplace (int dx, int dy) throws a.deplace (-3, 5) ;
ErrDepl
a = new Point (-3, 5) ;
{ if ( ((x+dx)<0) || ((y+dy)<0)) throw new
ErrDepl() ; a.affiche() ;}
x += dx ; y += dy ;} catch (ErrConst e)
public void affiche() { System.out.println ("Erreur construction ") ;
{ System.out.println ("coordonnees : " + x + " System.exit (-1) ;}
" + y) ;}
catch (ErrDepl e)
private int x, y ;}
{ System.out.println ("Erreur deplacement ") ;
class ErrConst extends Exception{ }
System.exit (-1) ;}}}
class ErrDepl extends Exception{ }
coordonnees : 1 4
Programmation Objet Avancée (POA) Erreur deplacement 20

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Transmission d’information au gestionnaire
d’exception

• On peut transmettre une information au gestionnaire d’exception :


• par le biais de l’objet fourni dans l’instruction throw,
• par l’intermédiaire du constructeur de l’objet exception.

Programmation Objet Avancée (POA) 21

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Par le biais de l’objet fourni dans l’instruction throw

class Point public class Exinfo1

{ public Point(int x, int y) throws ErrConst { public static void main (String args[])

{ if ( (x<0) || (y<0)) throw new ErrConst(x, y) { try


; { Point a = new Point (1, 4) ;
this.x = x ; this.y = y ;} a.affiche() ;
public void affiche() a = new Point (-3, 5) ;
{ System.out.println ("coordonnees : " + x + " " a.affiche() ;}
+ y) ;}
catch (ErrConst e)
private int x, y ;
{ System.out.println ("Erreur construction
} Point") ;
class ErrConst extends Exception System.out.println (" coordonnees souhaitees : "
{ ErrConst (int abs, int ord) + e.abs + " " + e.ord) ;

{ this.abs = abs ; this.ord = ord ;} System.exit (-1) ;}}}

public int abs, ord ; coordonnees : 1 4

} Erreur construction Point


coordonnees souhaitees : -3 5
Programmation Objet Avancée (POA) 22

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Par l’intermédiaire du constructeur de l’objet exception
public class Exinfo2
class Point { public static void main (String args[])
{ public Point(int x, int y) throws ErrConst { try
{ if ( (x<0) || (y<0)) { Point a = new Point (1, 4) ;
throw new ErrConst("Erreur construction avec a.affiche() ;
coordonnees " + x + " " + y) ;
a = new Point (-3, 5) ;
this.x = x ; this.y = y ;}
a.affiche() ;
public void affiche()
}
{ System.out.println ("coordonnees : " + x +
" " + y) ; catch (ErrConst e)
} { System.out.println (e.getMessage()) ;
private int x, y ; System.exit (-1) ;
} }
class ErrConst extends Exception }
{ ErrConst (String mes) }
{ super(mes) ;}} coordonnees : 1 4
Erreur construction avec coordonnees -3 5
Programmation Objet Avancée (POA) 23

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Le bloc finally

• Le déclenchement d’une exception provoque un branchement inconditionnel au


gestionnaire, à quelque niveau qu’il se trouve. L’exécution se poursuit avec les
instructions suivant ce gestionnaire.
• Cependant, Java permet d’introduire, à la suite d’un bloc try, un bloc particulier
d’instructions qui seront toujours exécutées : Le bloc finally

Programmation Objet Avancée (POA) 24

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Le bloc finally

• Le bloc finally doit obligatoirement être placé après le dernier


gestionnaire:
• Soit après la fin "naturelle" du bloc try, si aucune exception n’a été déclenchée
(il peut s’agir d’une instruction de branchement inconditionnel telle que break
ou continue),
• Soit après le gestionnaire d’exception (à condition, bien sûr, que ce dernier n’ait
pas provoqué d’arrêt de l’exécution).

Programmation Objet Avancée (POA) 25

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Exemple 1

try { ..... }
catch (Ex e) { ..... }
finally
{ // instructions A
}

Programmation Objet Avancée (POA) 26

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Exemple 2

void f (...) throws Ex


{ .....
try
{ ..... }
finally
{ // instructions A }
.....
}

Programmation Objet Avancée (POA) 27

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Remarque
• Il est possible d’associer un bloc finally à un bloc try ne comportant aucun
gestionnaire d’exception. Dans ce cas, ce bloc est exécuté après la sortie du bloc
try, quelle que soit la façon dont elle a eu lieu :
try
{ .....
if (...) break ; // si ce break est exécuté, on exécutera d’abord
.....
}
finally // ce bloc finally
{ ..... }
..... // avant de passer à cette instruction

Programmation Objet Avancée (POA) 28

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information
Informations complémentaires
• Il est possible de rencontrer des instructions return à la fois dans un bloc try et dans un
bloc finally, comme dans :
try
{ .....
return 0 ; // provoque d’abord l’exécution
}
finally // de ce bloc finally
{ .....
return -1 ; // et un retour avec la valeur -1
}

Programmation Objet Avancée (POA) 29

ENP d’Oran -Informatique-


Ingénierie et Management des Systèmes d’Information

Vous aimerez peut-être aussi