You are on page 1of 33

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Le mcanisme dexception du langage Java


Cours Java - F. Michel 1 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Plan
1

Introduction aux exceptions en Java Exemples de code avec gestion des exceptions Crer ses propres exceptions Instruction try/catch/nally java.lang.Error et java.lang.RuntimeException Avantages lis aux exceptions

Cours Java - F. Michel 2 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Quest-ce quune exception en Java ?


Dnition
Une exception est un vnement, se produisant lors de lexcution dun programme, qui interrompt lenchanement normal des instructions

Lobjet Exception
Lorsquune erreur se produit dans une mthode, celle-ci cre un objet Exception qui contient des informations sur lerreur survenue :
le type de lerreur : objet null, dpassement de tableau, etc. la trace dexcution du programme : la stack trace

Laction de crer un objet Exception et de le passer au systme dexcution est appele lever/lancer une exception (throwing an exception)

Cours Java - F. Michel 4 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Gestion dune exception

Rcupration de lexception
Lorsquune exception est leve, le systme dexcution tente de trouver un handler pour cette exception : c--d. une mthode pouvant la grer. Pour cela, il cherchera dans les mthodes qui ont t appeles jusqu lexception : the call stack (la pile dappels)

Cours Java - F. Michel 5 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Gestion dune exception

The call stack : exemple

Cours Java - F. Michel 6 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Gestion dune exception


Recherche dans la call stack
Le systme dexcution va donc chercher dans la call stack une mthode contenant un bout de code capable de grer lexception leve. Ce bout de code est appel exception handler. La recherche commence par la mthode o lerreur est apparue. Cette recherche continue dans lordre inverse des mthodes contenues dans la call stack jusqu trouver un exception handler appropri. Un exception handler est appropri sil est capable de grer le type dexception renvoy. Si un exception handler appropri est trouv, on dit quil attrape lexception : catch the exception. Sinon, le programme sarrte en afchant les informations associes lexception : type et stack trace (enchanement des appels de mthode).
Cours Java - F. Michel 7 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Gestion dune exception

Recherche dun exception handler dans la call stack

Cours Java - F. Michel 8 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Le "Catch or specify requirement"


Du code Java valide doit ncessairement inclure la gestion des exceptions et respecter ainsi le Catch or specify requirement : Tout code susceptible de renvoyer une exception doit tre contenu soit :
dans une instruction try/catch qui dnit ainsi le handler appropri. dans une mthode spciant explicitement quelle peut renvoyer une exception : il faut inclure le mot cl throws, suivi du type dexception renvoye, dans la signature de la mthode. Exemple : public void setAge(int age) throws NegativeAgeException

D U CODE NE RESPECTANT PAS CETTE RGLE NE COMPILE PAS !

Cours Java - F. Michel 9 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Exemples
Le constructeur de la classe java.io.PrintWriter est susceptible, par dnition (cf. api), de renvoyer une exception du type java.io.IOException. Cest pourquoi le code suivant ne peut pas tre compil. Il ne respecte pas le catch or specify requirement ! Exemple de code erron
package prog ; import java . io . F i l e W r i t e r ; import java . io . P r i n t W r i t e r ; public class TestingExceptions { public void w r i t e F i l e T e s t i n g ( ) { P r i n t W r i t e r o u t = new P r i n t W r i t e r ( new F i l e W r i t e r ( " O u t F i l e . t x t " ) ) ; out . p r i n t ( " t e s t " ) ; } }

Cours Java - F. Michel 11 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Solution 1 : gestion active avec try/catch


Solution 1 : try/catch
package prog ; import java . io . F i l e W r i t e r ; import java . io . P r i n t W r i t e r ; i m p o r t j a v a . i o . IOException ; / / I l f a u t i m p o r t e r l a c l a s s e de l e x c e p t i o n public class TestingExceptions { public void w r i t e F i l e T e s t i n g ( ) { P r i n t W r i t e r out = n u l l ; try { o u t = new P r i n t W r i t e r ( new F i l e W r i t e r ( " O u t F i l e . t x t " ) ) ; } c a t c h ( IOException e ) { System . o u t . p r i n t l n ( " e r r e u r o u v e r t u r e f i c h i e r " ) ; e . p r i n t S t a c k T r a c e ( ) ; / / a f f i c h a g e de l a c a l l s t a c k pour debugger } i f ( o u t ! = n u l l ) { / / i l e s t p r e f e r a b l e de v e r i f i e r out . p r i n t ( " t e s t " ) ; } } }
Cours Java - F. Michel 12 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Solution 2 : gestion passive avec throws


Solution 2 : throws dans la signature
package prog ; import java . io . F i l e W r i t e r ; import java . io . P r i n t W r i t e r ; i m p o r t j a v a . i o . IOException ; public class TestingExceptions { p u b l i c v o i d w r i t e F i l e T e s t i n g ( ) throws IOException { P r i n t W r i t e r o u t = new P r i n t W r i t e r ( new F i l e W r i t e r ( " O u t F i l e . t x t " ) ) ; out . p r i n t ( " t e s t " ) ; }

Remarque
Prfrez la solution 1. Il est toujours plus sr de grer soi-mme les exceptions. Ici la gestion est dlgue la mthode appelante.
Cours Java - F. Michel 13 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Nature des exceptions en Java


Hirachie des exceptions
Les exceptions sont des objets comme les autres en Java (leur gestion mise part) Il est donc possible de crer ses propres exceptions et de les lancer (throw) lors de lexcution dun programme. une exception est un objet qui hrite de la classe java.lang.Throwable
java.lang.Throwable

Il existe deux sous-classes prdnies dans le JDK : java.lang.Error et java.lang.Exception les exceptions "classiques" sont des sous-classes de java.lang.Exception les exceptions sous-classes de java.lang.Error stoppent un programme lorsquelles sont lances. (on ne sen sert que trs rarement).
Cours Java - F. Michel 15 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Crer ses propres exceptions

Cration dune nouvelle exception


Pour crer sa propre classe dexception, il suft donc de crer une classe qui hrite de java.lang.Exception La plupart du temps, on cre une nouvelle exception pour
1

grer, par programmation (et non par message derreur), les utilisations incorrectes dune mthode. et surtout prvenir lutilisateur de la mthode que certaines utilisations sont incorrectes et quelles doivent tre gres explicitement.

Cours Java - F. Michel 16 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Crer ses propres exceptions


Soit la classe suivante : Personne.java
package prog ; p u b l i c c l a s s Personne { p r i v a t e i n t age ; / / must be >= 0 p u b l i c Personne ( i n t age ) { t h i s . age = age ; } p u b l i c v o i d setAge ( i n t age ) { t h i s . age = age ; } }

Cours Java - F. Michel 17 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Cration dune nouvelle classe dexception

NegativeAgeException.java
package prog ; p u b l i c c l a s s NegativeAgeException extends E x c ep t i o n { }

Cours Java - F. Michel 18 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Lancer une exception


Pour lancer une exception lors de lexcution il faut utiliser le mot cl throw avec lexception cre pour la circonstance :

Personne.java
. . . p u b l i c v o i d setAge ( i n t age ) throws NegativeAgeException { i f ( age < 0 ) { throw ( new NegativeAgeException ( ) ) ; / / s o r t de l a methode } t h i s . age = age ; / / execute seulement s i age >= 0 } . . .

Cours Java - F. Michel 19 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Nouvelle utilisation de la mthode


Lutilisation de la mthode est maintenant scurise : elle implique le respect du catch or specify requirement : TestPersonne.java
package prog ; p u b l i c c l a s s TestPersonne { p u b l i c s t a t i c v o i d main ( S t r i n g [ ] args ) { Personne pers = new Personne ( 1 0 ) ; try { pers . setAge ( 1); } c a t c h ( NegativeAgeException e ) { e . printStackTrace ( ) ; } } }

Cours Java - F. Michel 20 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Excution
TestPersonne.java
package prog ; p u b l i c c l a s s TestPersonne { p u b l i c s t a t i c v o i d main ( S t r i n g [ ] args ) { Personne pers = new Personne ( 1 0 ) ; try { pers . setAge ( 1); } c a t c h ( NegativeAgeException e ) { e . printStackTrace ( ) ; } } }

Rsultat : (lge na pas t modi !)


prog . NegativeAgeException a t prog . Personne . setAge ( Personne . j a v a : 1 3 ) a t prog . TestPersonne . main ( TestPersonne . j a v a : 8 )

Cours Java - F. Michel 21 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

La classe java.lang.Exception en dtail


Il est possible de personnaliser trs simplement une exception grce aux mthodes qui existent dj dans la classe java.lang.Exception :
java.lang.Exception

java.lang.Exception

Cours Java - F. Michel 22 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Personnalisation du message derreur

La classe java.lang.Exception possde un constructeur qui permet dinitialiser le message qui sera obtenu : NegativeAgeException.java
package prog ; p u b l i c c l a s s NegativeAgeException extends E x c ep t i o n { p u b l i c NegativeAgeException ( S t r i n g message ) { super ( message ) ; } }

Cours Java - F. Michel 23 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Cration dun message derreur personnalis

Nouvelle version de Personne.java


. . . p u b l i c v o i d setAge ( i n t age ) throws NegativeAgeException { i f ( age < 0 ) { throw ( new NegativeAgeException ( " e r r e u r : l age d o i t e t r e > 0 , v a l e u r e n t r e e : " +age ) ) ; } t h i s . age = age ; } . . .

Cours Java - F. Michel 24 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Excution
TestPersonne.java
package prog ; p u b l i c c l a s s TestPersonne { p u b l i c s t a t i c v o i d main ( S t r i n g [ ] args ) { Personne pers = new Personne ( 1 0 ) ; try { pers . setAge ( 1); } c a t c h ( NegativeAgeException e ) { e . printStackTrace ( ) ; } } }

Rsultat :
prog . NegativeAgeException : e r r e u r : l age d o i t e t r e > 0 , v a l e u r e n t r e e : 1 a t prog . Personne . setAge ( Personne . j a v a : 1 3 ) a t prog . TestPersonne . main ( TestPersonne . j a v a : 8 )

Cours Java - F. Michel 25 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Instruction try/catch/nally

Le bloc try
try { code } c a t c h and f i n a l l y b l o c k s . . .

Cours Java - F. Michel 27 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Instruction try/catch/nally
Les blocs catch
try { } c a t c h ( ExceptionType name ) { } c a t c h ( AnotherExceptionType name ) { }

Exemple
try { . . . } c a t c h ( F il e N o t F o u n d E x c e p t i o n e ) { System . e r r . p r i n t l n ( " F i l e N o t F o u n d E x c e p t i o n : " + e . getMessage ( ) ) ; } c a t c h ( IOException e ) { System . e r r . p r i n t l n ( " Caught IOException : " + e . getMessage ( ) ) ; } Cours Java - F. Michel 28 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Instruction try/catch/nally
Le block nally est un block optionnel contenant des instructions qui seront toujours excutes quelque soit le rsultat du try : Exemple pour une ouverture de chier
try { code } catch { code } finally { i f ( out != n u l l ) { System . o u t . p r i n t l n ( " C l o s i n g P r i n t W r i t e r " ) ; out . close ( ) ; } else { System . o u t . p r i n t l n ( " P r i n t W r i t e r n o t open " ) ; } }

Cours Java - F. Michel 29 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Instruction try/catch/nally
Il permet donc dviter dcrire plusieurs fois le mme code. Notamment, il permet de sassurer que les ressources ventuellement utilises sont toujours libres : Exemple sans nally (code redondant)
try { ... out . close ( ) ; / / Don t do t h i s ; i t d u p l i c a t e s code . } c a t c h ( F ile Not Fou ndE xce pti on e ) { out . close ( ) ; / / Don t do t h i s ; i t d u p l i c a t e s code . System . e r r . p r i n t l n ( " Caught : F ile Not Fou ndE xce pti on : " + e . getMessage ( ) ) ; } c a t c h ( IOException e ) { out . close ( ) ; / / Don t do t h i s ; i t d u p l i c a t e s code . System . e r r . p r i n t l n ( " Caught " +e . getMessage ( ) ) ; }

Cours Java - F. Michel 30 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Classes dexceptions particulires


La documentation de la classe java.lang .Integer indique que la mthode parseInt peut renvoyer lexception java.lang.NumberFormatException (cf. api). Pourtant le code suivant, qui semble ne pas respecter le catch or specify requirement, compile sans problme : Testing.java
package prog ; p u b l i c c l a s s T e s t i n g { / / pas de throws p u b l i c s t a t i c v o i d main ( S t r i n g [ ] args ) { I n t e g e r . p a r s e I n t ( " 10 " ) ; / / pas de t r y / c a t c h } }

Cours Java - F. Michel 32 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Classes dexceptions particulires

En fait, il existe trois types dexceptions diffrents : 1. Les exceptions classiques


Les exceptions "classiques" (checked exceptions) qui ncessitent de respecter le try or specify requirement I.e Toutes les exceptions sauf les exceptions de type java.lang.Error, java.lang.RuntimeException et leurs sous-classes.

Cours Java - F. Michel 33 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Classes dexceptions particulires

2. Les exceptions de type java.lang.Error


Elles se produisent dans des conditions exceptionnelles qui ne sont pas directement lies lapplication (ex : java.lang .OutOfMemoryError , java.lang .VirtualMachineError ) Elles ne sont gnralement pas prises en comptent dans le code : il est normal que le programme quitte dans ces cas l.

Cours Java - F. Michel 34 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Classes dexceptions particulires

3. Les exceptions de type java.lang.RuntimeException


Elles se produisent dans des conditions exceptionnelles qui sont lies lapplication ex : mauvaise utilisation dune API, bug de programmation, etc. ex : java.lang.NumberFormatException, java.lang.ArrayIndexOutOfBoundsException

Cours Java - F. Michel 35 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Avantages lis aux exceptions


Le principal avantage li lutilisation du mcanisme dexception est de permettre une sparation explicite entre la logique du programme et la gestion dvenements qui sortent de cette logique. Soit le programme suivant :
readFile { open t h e f i l e ; determine i t s s i z e ; a l l o c a t e t h a t much memory ; read t h e f i l e i n t o memory ; close the f i l e ; }

Toutes ces instructions sont potentiellement source de problme ; il faut pouvoir les grer.
Cours Java - F. Michel 37 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Programmation sans gestion dexceptions


errorCodeType r e a d F i l e { i n i t i a l i z e errorCode = 0 ; open t h e f i l e ; i f ( theFileIsOpen ) { determine t h e l e n g t h o f t h e f i l e ; i f ( gotTheFileLength ) { a l l o c a t e t h a t much memory ; i f ( gotEnoughMemory ) { read t h e f i l e i n t o memory ; i f ( readFailed ) { errorCode = 1; } } else { errorCode = 2; } } else { errorCode = 3; } close the f i l e ; i f ( t h e F i l e D i d n t C l o s e && errorCode == 0 ) { errorCode = 4; } else { errorCode = errorCode and 4; } } else { errorCode = 5; } r e t u r n errorCode ; } Cours Java - F. Michel 38 / 39

Introduction

Exemples

Cration

Instruction try/catch/nally

Error et RuntimeException

Avantages

Avantages lis aux exceptions


Programmation avec gestion des exceptions
readFile { try { open t h e f i l e ; determine i t s s i z e ; a l l o c a t e t h a t much memory ; read t h e f i l e i n t o memory ; close the f i l e ; } catch ( fileOpenFailed ) { doSomething ; } catch ( sizeDeterminationFailed ) { doSomething ; } catch ( memoryAllocationFailed ) { doSomething ; } catch ( readFailed ) { doSomething ; } catch ( f i l e C l o s e F a i l e d ) { doSomething ; } }
Cours Java - F. Michel 39 / 39

You might also like