0% ont trouvé ce document utile (0 vote)
107 vues46 pages

Cours Java Exception

Transféré par

losus007
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
107 vues46 pages

Cours Java Exception

Transféré par

losus007
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

Java : les exceptions

Achref El Mouelhi

Docteur de l’université d’Aix-Marseille


Chercheur en Programmation par contrainte (IA)
Ingénieur en Génie logiciel

[email protected]

H & H: Research and Training 1 / 33


Plan

1 Introduction

2 Capture d’exception

3 Les exceptions personnalisées

4 Les instructions multi-catch

5 Les exceptions paramétrées

6 Le bloc finally

H & H: Research and Training 2 / 33


Introduction

Java

Une exception, c’est quoi ?


I c
C’est une erreur qui se produit pendantU
H
L de notre
Eécution
l’ex
programme
L MO
Une exception dansre
E
unfprogramme implique généralement son
A c
arrêt d’exécution
h
c

H & H: Research and Training 3 / 33


Introduction

Java

Comment faire pour poursuivre l’exécution ?


I c

EL H
Repérer les blocs pouvant générer une exception
U
MO
Capturer l’exception correspondante
L
h
Afficher un message r e f Eà cette exception
relatif
A c
c
Continuer l’exécution

H & H: Research and Training 4 / 33


Introduction

Java
Exception : exemple
public class Test {
public static void main(String[] args) {
int x = 5, y = 0;
System.out.print(x / y);
I c

}
System.out.println("Fin de calcul");
ELH
U
MO
}

Le message affiché à l’exécution


f E L
chre
c A

H & H: Research and Training 5 / 33


Introduction

Java
Exception : exemple
public class Test {
public static void main(String[] args) {
int x = 5, y = 0;
System.out.print(x / y);
I c

}
System.out.println("Fin de calcul");
ELH
U
MO
}

Le message affiché à l’exécution


f E L
chre
c A
Exception in thread ”main” java.lang.ArithmeticException : / by zero at

test.FirstClass.main( FirstClass.java :4 )

H & H: Research and Training 5 / 33


Introduction

Java
Exception : exemple
public class Test {
public static void main(String[] args) {
int x = 5, y = 0;
System.out.print(x / y);
I c

}
System.out.println("Fin de calcul");
ELH
U
MO
}

Le message affiché à l’exécution


f E L
chre
c A
Exception in thread ”main” java.lang.ArithmeticException : / by zero at

test.FirstClass.main( FirstClass.java :4 )

Constatation
Le message Fin de calcul n’a pas été affiché
La division par zéro déclenche une exception ArithmeticException

H & H: Research and Training 5 / 33


Capture d’exception

Java

Comment faire pour capturer une exception ?


I c
EL
Utiliser un bloc try { ... } catch { ... } H
U
Oinstruction susceptible de
Le try { ... } pour entourer
déclencher une exceptionE L Mune
f
Le catch {A...chr}epour capturer l’exception et afficher un
messagec qui lui correspond

H & H: Research and Training 6 / 33


Capture d’exception

Java
Exception : exemple
public class Test {
public static void main(String[] args) {
int x = 5, y = 0;
try {
System.out.println(x / y);
I c

}
catch (ArithmeticException e) {
ELH
U
MO
System.out.println("Exception : Division par zéro ");
}

E L
System.out.println("Fin de calcul");
f
hre
}
}
c
c A

H & H: Research and Training 7 / 33


Capture d’exception

Java
Exception : exemple
public class Test {
public static void main(String[] args) {
int x = 5, y = 0;
try {
System.out.println(x / y);
I c

}
catch (ArithmeticException e) {
ELH
U
MO
System.out.println("Exception : Division par zéro ");
}

E
System.out.println("Fin de calcul");
f L
hre
}
}
c
c A

Le message affiché à l’exécution

Exception : Division par zéro


Fin de calcul

H & H: Research and Training 7 / 33


Capture d’exception

Java
Exception : exemple
public class Test {
public static void main(String[] args) {
int x = 5, y = 0;
try {
System.out.println(x / y);
I c

}
catch (ArithmeticException e) {
ELH
U
MO
System.out.println("Exception : Division par zéro ");
}

E
System.out.println("Fin de calcul");
f L
hre
}
}
c
c A

Le message affiché à l’exécution

Exception : Division par zéro


Fin de calcul

Constatation
L’exception a été capturée
Le message Fin de calcul a été affiché
H & H: Research and Training 7 / 33
Capture d’exception

Java
Et si je ne connais pas le type d’exception

public class Test {


public static void main(String[] args) {
int x = 5, y = 0;
try {
System.out.println(x / y);
I c

}
catch (Exception e) {
ELH
U
MO
System.out.println("Exception : Division par zéro ");
}

f E L
System.out.println("Fin de calcul");

hre
}
}
c
c A

H & H: Research and Training 8 / 33


Capture d’exception

Java
Et si je ne connais pas le type d’exception

public class Test {


public static void main(String[] args) {
int x = 5, y = 0;
try {
System.out.println(x / y);
I c

}
catch (Exception e) {
ELH
U
MO
System.out.println("Exception : Division par zéro ");
}

f E
System.out.println("Fin de calcul"); L
hre
}
}
c
c A

Le même message sera affiché

Exception : Division par zéro


Fin de calcul

H & H: Research and Training 8 / 33


Capture d’exception

Java
Et si je ne connais pas le type d’exception

public class Test {


public static void main(String[] args) {
int x = 5, y = 0;
try {
System.out.println(x / y);
I c

}
catch (Exception e) {
ELH
U
MO
System.out.println("Exception : Division par zéro ");
}

f E
System.out.println("Fin de calcul"); L
hre
}
}
c
c A

Le même message sera affiché

Exception : Division par zéro


Fin de calcul

Constatation
La classe Exception peut être utilisée

H & H: Research and Training 8 / 33


Capture d’exception

Java
Utiliser des méthodes de la classe Exception

public class Test {


public static void main(String[] args) {
int x = 5, y = 0;
try {
I c

System.out.println(x / y);
ELH
}
U
catch (Exception e) {
L MO
E
System.out.println("Exception : " + e.getMessage());
f
}
chre
c A
System.out.println("Fin de calcul");

}
}

H & H: Research and Training 9 / 33


Capture d’exception

Java
Utiliser des méthodes de la classe Exception

public class Test {


public static void main(String[] args) {
int x = 5, y = 0;
try {
I c

System.out.println(x / y);
ELH
}
U
catch (Exception e) {
L MO
E
System.out.println("Exception : " + e.getMessage());
f
}
chre
c A
System.out.println("Fin de calcul");

}
}

Le même message sera affiché

Exception : / by zero
Fin de calcul

H & H: Research and Training 9 / 33


Capture d’exception

Java
Utiliser des méthodes de la classe Exception

public class Test {


public static void main(String[] args) {
int x = 5, y = 0;
try {
I c

System.out.println(x / y);
ELH
}
U
catch (Exception e) {
e.printStackTrace();
L MO
f E
hre
}

c
System.out.println("Fin de calcul");

}
}
c A

H & H: Research and Training 10 / 33


Capture d’exception

Java
Utiliser des méthodes de la classe Exception

public class Test {


public static void main(String[] args) {
int x = 5, y = 0;
try {
I c

System.out.println(x / y);
ELH
}
U
catch (Exception e) {
e.printStackTrace();
L MO
f E
hre
}

c
System.out.println("Fin de calcul");

}
}
c A

Le message affiché est :

java.lang.ArithmeticException : / by zero
at test.FirstClass.main( FirstClass.java :49 )
Fin de calcul

H & H: Research and Training 10 / 33


Les exceptions personnalisées

Java

On a utilisé (ou vu) des exceptions prédéfinies


Exception I c

ELH
ArithmeticException U
L MO
NullPointerException
f E
c hre
c A

H & H: Research and Training 11 / 33


Les exceptions personnalisées

Java

On a utilisé (ou vu) des exceptions prédéfinies


Exception I c

ELH
ArithmeticException U
L MO
NullPointerException
f E
c hre
c A

On peut aussi définir nos exceptions personnalisées

H & H: Research and Training 11 / 33


Les exceptions personnalisées

Java
Considérons la classe Adresse suivante
package org.eclipse.model;

public class Adresse {


I c

private String rue;
private String ville; ELH
U
private String codePostal;
L MO
E
public Adresse(String rue, String codePostal,
f
String ville) {
c hre
c A
this.rue = rue;

this.ville = ville;
this.codePostal = codePostal;
}
// ensuite les getters/setters et autres méthodes
}

H & H: Research and Training 12 / 33


Les exceptions personnalisées

Java

Supposons que
codePostal doit contenir exactement 5 chiffres
I c

ELH
U
L MO
f E
c hre
c A

H & H: Research and Training 13 / 33


Les exceptions personnalisées

Java

Supposons que
codePostal doit contenir exactement 5 chiffres
I c

ELH
U
L MO
Démarche à faire
f E
c hre
c A
Créer notre propre exception (qui doit étendre la classe
Exception)
Dans le constructeur de Adresse, on lance une exception si
codePostal ne contient pas 5 chiffres

H & H: Research and Training 13 / 33


Les exceptions personnalisées

Java

Créons l’exception IncorrectCodePostalException dans un


package org.eclipse.exceptions

I c

public class IncorrectCodePostalException extends
Exception {
EL H
U
// le constructeur de L MOnouvelle exception
fE
cette
r e
public IncorrectCodePostalException(){
c h
c A
System.out.println("Le
exactement
code postal doit contenir
5 chiffres");
}
}

H & H: Research and Training 14 / 33


Les exceptions personnalisées

Java

Modifions le constructeur de la classe Adresse


public class Adresse {
// après les attributs
public Adresse(String rue, String ville, String
I c

codePostal) throws IncorrectCodePostalException
ELH
U
MO
{
if (codePostal.length() != 5)
f E L
hre
throw new IncorrectCodePostalException();
c
c A
this.rue = rue;

this.ville = ville;
this.codePostal = codePostal;
}
}
// il faut faire pareil dans setCodePostal()

H & H: Research and Training 15 / 33


Les exceptions personnalisées

Java
Testons tout cela dans le main()
public static void main(String[] args) {
Adresse a = null;
try {
I c

a = new Adresse ("rue de paradis", "Marseille",
ELH
U
MO
"1300");
}
f E L
hre
catch(IncorrectCodePostalException icpe) {
c
c A
icpe.printStackTrace();

}
}

H & H: Research and Training 16 / 33


Les exceptions personnalisées

Java
Testons tout cela dans le main()
public static void main(String[] args) {
Adresse a = null;
try {
I c

a = new Adresse ("rue de paradis", "Marseille",
ELH
U
MO
"1300");
}
f E L
hre
catch(IncorrectCodePostalException icpe) {
c
c A
icpe.printStackTrace();

}
}
Le message affiché est :

Le code postal doit contenir exactement 5 chiffres

H & H: Research and Training 16 / 33


Les instructions multi-catch

Java

I c

On peut rajouter une deuxième condition
E LH
U
MO 5 chiffres
codePostal doit contenir exactement
L
r e fE
rue doit être une chaı̂ne
h
en majuscule
A c
c

H & H: Research and Training 17 / 33


Les instructions multi-catch

Java

Créons une deuxième exception IncorrectStreetNameException


dans le package org.eclipse.exceptions

I c

public class IncorrectStreetNameException extends
Exception {
EL H
U
L MO
re f
System.out.print("Le
E
public IncorrectStreetNameException()
nom de la rue
{
doit être en
c h
c A
majuscule");
}
}

H & H: Research and Training 18 / 33


Les instructions multi-catch

Java
Modifions le constructeur de la classe Adresse
public class Adresse {
// après les attributs
public Adresse(String rue, String ville, String
I c

codePostal) throws IncorrectCodePostalException
ELH
, IncorrectStreetNameException {
U
if (codePostal.length() != 5)
L MO
f E
throw new IncorrectCodePostalException();
c hre
if(!rue.equals(rue.toUpperCase()))
c A

throw new IncorrectStreetNameException();
this.rue = rue;
this.ville = ville;
this.codePostal = codePostal;
}
}

H & H: Research and Training 19 / 33


Les instructions multi-catch

Java

Re-testons tout cela dans le main()


public static void main(String[] args) {
try {
I c

Adresse a = new Adresse ("paradis", "Marseille",
"1300"); ELH
U
}
L MO
E
catch(IncorrectCodePostalException icp) {
f
icp.printStackTrace();
c hre
}
c A

catch(IncorrectStreetNameException isn) {
isn.printStackTrace();
}
}

H & H: Research and Training 20 / 33


Les instructions multi-catch

Java

Depuis Java 7, on peut écrire :


public static void main(String[] args) {
try {
I c

Adresse a = new Adresse ("paradis", "Marseille",
ELH
U
"1300");
L MO
}
f E
hre
catch(IncorrectCodePostalException |
c
c A
IncorrectStreetNameException e) {

e.printStackTrace();
}
}

H & H: Research and Training 21 / 33


Les exceptions paramétrées

Java

I c
Question
ELH
Comment faire si on veut afficher lesM
U
O qui ont déclenché
valeurs
l’exception dans le message ?E L
c h ref
c A

H & H: Research and Training 22 / 33


Les exceptions paramétrées

Java

Modifions la première exception


IncorrectCodePostalException
I c

public class IncorrectCodePostalException extends
ELH
Exception {
U
// le constructeur de cette nouvelle exception
L MO
f E
public IncorrectCodePostalException(String cp){
c hre
System.out.println("Le code postal ’" + cp + "’

}
c A

doit contenir exactement 5 chiffres");

H & H: Research and Training 23 / 33


Les exceptions paramétrées

Les exceptions paramétrées

Modifions la deuxième exception


IncorrectStreetNameException
I c

public class IncorrectStreetNameException extends
ELH
U
MO
Exception {

f E L
public IncorrectStreetNameException(String rue) {

hre
System.out.print("Le nom de la rue ’" + rue + "’
c
c A
doit être en majuscule");

}
}

H & H: Research and Training 24 / 33


Les exceptions paramétrées

Java
Modifions le constructeur de la classe Adresse
public class Adresse {
// après les attributs
public Adresse(String rue, String ville, String
I c

codePostal) throws IncorrectCodePostalException
ELH
, IncorrectStreetNameException {
U
if (codePostal.length()!=5)
L MO
f E
throw new IncorrectCodePostalException(
codePostal);
c hre
c A
if(!rue.equals(rue.toUpperCase()))

throw new IncorrectStreetNameException(rue);
this.rue = rue;
this.ville = ville;
this.codePostal = codePostal;
}
}
H & H: Research and Training 25 / 33
Les exceptions paramétrées

Java
Pour tester
public static void main(String[] args) {
try {
Adresse a = new Adresse ("paradis", "Marseille",
I c

"1300");
ELH
U
MO
}
catch(IncorrectCodePostalException |
f E L
hre
IncorrectStreetNameException e) {
c
c A
e.printStackTrace();

}
}

H & H: Research and Training 26 / 33


Les exceptions paramétrées

Java
Pour tester
public static void main(String[] args) {
try {
Adresse a = new Adresse ("paradis", "Marseille",
I c

"1300");
ELH
U
MO
}
catch(IncorrectCodePostalException |
f E L
hre
IncorrectStreetNameException e) {
c
c A
e.printStackTrace();

}
}
Le message affiché est :

Le code postal ’1300’ doit contenir exactement 5 chiffres

H & H: Research and Training 26 / 33


Les exceptions paramétrées

Java

Exercice I c
EL H
O U
Créer une nouvelle classe d’exception AdresseException pour
L M
fusionner et remplacer les deux exceptions
e
IncorrectCodePostalException
r f E et
c h
IncorrectStreetNameException
A
c

H & H: Research and Training 27 / 33


Les exceptions paramétrées

Java
Contenu de la classe AdresseException

package org.eclipse.exception;

public class AdresseException extends Exception {

public AdresseException(String cp, String rue) {


I c

EL
System.out.println("Le code postal ’" + cp + "’ doit contenirH
exactement 5 chiffres.");
U
MO
System.out.print("Le nom de la rue ’" + rue + "’ doit être en

}
majuscule.");

f E L
c hre
c A
public AdresseException(int index, String value) {


if (index == 0)
System.out.println("Le code postal ’" + value + "’ doit contenir
exactement 5 chiffres.");
else
System.out.print("Le nom de la rue ’" + value + "’ doit être en
majuscule.");
}
}

H & H: Research and Training 28 / 33


Les exceptions paramétrées

Contenu de la classe Adresse

public class Adresse {


// les attributs
public Adresse(String rue, String codePostal, String ville) throws
AdresseException {
if(!rue.equals(rue.toUpperCase()) && codePostal.length() != 5)
throw new AdresseException(codePostal, rue);
setRue(rue);
I c

setCodePostal(codePostal);
this.ville = ville;
ELH
}
U
public void setRue(String rue) throws AdresseException {
L MO
if (!rue.equals(rue.toUpperCase()))
f E
hre
throw new AdresseException(1, rue);
this.rue = rue;
c
c A
}

public void setCodePostal(String codePostal) throws AdresseException
{
if (codePostal.length() != 5)
throw new AdresseException(0, codePostal);
this.codePostal = codePostal;
}
// + les autres getters + setters + toString()
}

H & H: Research and Training 29 / 33


Les exceptions paramétrées

Java
Testons tout cela dans le main()
public static void main(String[] args) {
Adresse a = null;
try {
a = new Adresse ("rue de paradis", "Marseille", "1300");
}
I c

catch (AdresseException e) {
ELH
e.printStackTrace(); U
}
L MO
}
f E
c hre
c A

H & H: Research and Training 30 / 33


Les exceptions paramétrées

Java
Testons tout cela dans le main()
public static void main(String[] args) {
Adresse a = null;
try {
a = new Adresse ("rue de paradis", "Marseille", "1300");
}
I c

catch (AdresseException e) {
ELH
e.printStackTrace(); U
}
L MO
}
f E
A c hre
Le message
c
affiché est :

Le code postal ’1300’ doit contenir exactement 5 chiffres.


Le nom de la rue ’paradis’ doit être en
majuscule.org.eclipse.exception.AdresseException
at org.eclipse.model.Adresse.<init>(Adresse.java:12)
at org.eclipse.test.Main.main(Main.java:11)

H & H: Research and Training 30 / 33


Le bloc finally

Java

I c

H
EL qu’une exception
U
soit levée ou non L MO
À utiliser quand on veut exécuter une instruction

h r e fE
A c
c

H & H: Research and Training 31 / 33


Le bloc finally

Java
Exemple
public class Test {
public static void main(String[] args) {
int x = 5, y = 0;
try {
I c

System.out.println(x / y);
ELH
U
}
L MO
catch (Exception e) {
f E
hre
System.out.println("Division par zéro");
c
c A
}
finally{
System.out.println("Instruction exécutée systé
matiquement");
}
}
}
H & H: Research and Training 32 / 33
Le bloc finally

Java

I c
Remarque
E LH
U
return qui forcera l’arrêt de l’exL MOdu sicode.
Le bloc finally peut s’avérer intéressant le catch contient un

re
(finally) sera exécuté. f E écution Malgré cela, ce bloc

c h
c A

H & H: Research and Training 33 / 33

Vous aimerez peut-être aussi