Académique Documents
Professionnel Documents
Culture Documents
Cours7 POA
Cours7 POA
• Définition
• Déroulement
• Les exceptions de type RunTimeException
• Définition et lancement d’exceptions utilisateurs (throw et throws)
• Gestion de plusieurs exceptions
• 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
•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
• 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.
• 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);
}
• 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.
• 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
{ public Point(int x, int y) throws ErrConst { public static void main (String args[])
try { ..... }
catch (Ex e) { ..... }
finally
{ // instructions A
}