Introduction Exemples Création Instruction try/catch/finally Error et RuntimeException AvantagesLe mécanisme d’exception dulangage JavaCours Java - F. Michel1 / 39Introduction Exemples Création Instruction try/catch/finally Error et RuntimeException AvantagesPlan1 Introduction aux exceptions en Java2 Exemples de code avec gestion des exceptions3 Créer ses propres exceptions4 Instruction try/catch/finally5 java.lang.Error et java.lang.RuntimeException6 Avantages liés aux exceptionsCours Java - F. Michel2 / 39Introduction Exemples Création Instruction try/catch/finally Error et RuntimeException AvantagesQu’est-ce qu’une exception en Java ?DéfinitionUne exception est un événement, se produisant lors de l’exécution d’unprogramme, qui interrompt l’enchaînement normal des instructionsL’objet ExceptionLorsqu’une erreur se produit dans une méthode, celle-ci crée un objetException qui contient des informations sur l’erreur survenue :le type de l’erreur : objet null, dépassement de tableau, etc.la trace d’exécution du programme : la stack traceL’action de créer un objet Exception et de le passer au systèmed’exécution est appelée lever/lancer une exception (throwing anexception)Cours Java - F. Michel4 / 39Introduction Exemples Création Instruction try/catch/finally Error et RuntimeException AvantagesGestion d’une exceptionRécupération de l’exceptionLorsqu’une exception est levée, le système d’exécution tente de trouverun handler pour cette exception : ...
Création Instruction try/catch/finally Error et RuntimeException
Gestion d’une exception
The
call
stack
:
exemple
Avantages
Cours Java - F. Michel
6 / 39
Ce bout de code est appeléexception handler.
Le système d’exécution va donc chercher dans la call stack une méthode contenant un bout de code capable de gérer l’exception levée.
Recherche dans la call stack
Cours Java - F. Michel
Si un exception handler approprié est trouvé, on dit qu’il attrape l’exception :catch the exception. Sinon, le programme s’arrête en affichant les informations associées à l’exception : type et stack trace (enchaînement des appels de méthode).
Un exception handler est approprié s’il estcapable de gérer le type d’exception renvoyé.
Cette recherche continue dans l’ordre inverse des méthodes contenues dans la call stack jusqu’à trouver un exception handler approprié.
La recherche commence par la méthode où l’erreur est apparue.
Création Instruction try/catch/finally Error et RuntimeException
Gestion d’une exception
Recherche d’un exception handler dans call stack
la
Avantages
Cours Java - F. Michel
8 / 39
ntagesODUCSEEPNEREPTSATCNAERÈGCETTCOMPLENE
D
!
dans une instructiontry/catchqui définit ainsi le handler approprié.
dans une méthode spécifiant explicitement qu’elle peut renvoyer une exception : il faut inclure le mot cléthrows, suivi du type d’exception renvoyée, dans la signature de la méthode. Exemple : public void setAge(int age)throws NegativeAgeException
Du code Java valide doitsecériasntemeninclure la gestion des exceptions et respecter ainsi leCatch or specify requirement:
Tout code susceptible de renvoyer une exception doit être contenu soit :
p u b l i c c l a s sT e s t i n g E x c e p t i o n s {
i m p o r t . i o . F i l e W r i t e r ;j a v ai m p o r ti o . P r i n t W r i t e r ; . j a v a
Le constructeur de la classe java.io.PrintWriter est susceptible, par définition (cf. api), de renvoyer une exception du type java.io.IOException. C’est pourquoi le code suivantne peut pas être compilé. Il !ne respecte pas le catch or specify requirement
Exemple de code erroné
p u b l i c v o i d ) { (T e s t i n gw r i t e F i l e P r i n t W r i t e r o u t =newn t W r i t e r (P r i newF i l e W r i t x t " ) ) ;e r ( " O u t F i l e . t o u t . p r i n t ( " t e s t " ) ; }
p u b l i c c l a s s {g E x c e p t i o n sT e s t i n
i m p o r t . i o . F i l e W r i t e r ;j a v ai m p o r tj a v a . i o . P r i n t W r i t e r ; i m p o r tj a v a ;c e p t i o n O E x . i o . I l I/ / m p o r t e r i a u t f l a c l a s s e de l ’ e x c e p t i o n
Cours Java - F. Michel
p u b l i c v o i dT e s t i n gw r i t e F i l e ) { ( P r i n t W r i t e r o u t =n u l l; t r y{ o u t =newP r i n t W r i t e r (newF i l e W r i t e r ( " O u t F i l e . t x t " ) ) ; }c a t c h { ) ec e p t i o n( I O E x 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 c/ / a f f i c h a g e de l s a l l pour debugger t a c k } i f( o u t ! =n u l l) {r i f i e r p r e f e r a b l e de v e i l e s t/ / o u t . p r i n t ( " t e s t " ) ; }
i m p o r t . i o . F i l e W r i t e r ;j a v ai m p o r ti o . P r i n t W r i t e r ; . j a v a i m p o r tj a v a . i o . I O E x c e p t i o n ;
Solution 2 : gestion passive avec throws
p u b l i c v o i dT e s t i n gw r i t e F i l e ) (t h r o w sI O E x c e p t i o n { P r i n t W r i t e r o u t =newP r i n t W r i t e r (new x t " te r ( " O u t F i l e .F i l e W r i t ) ) ; o u t . p r i n t ( " t e s t " ) ; }
p u b l i c c l a s s {g E x c e p t i o n sT e s t i n
Préférez la solution 1. Il est toujours plus sûr de gérer soi-même les exceptions. Ici la gestion est déléguée à la méthode appelante.