Langage JAVA
Prof: R. EL AYACHI
Département d’Informatique
Faculté des Sciences et Techniques
Béni Mellal
1
Chapitre 4: Exception
1. Définition
2. Hiérarchie des exceptions
3. Quelques classes d’exception
4. Attraper une exception
2
Prof: R. EL AYACHI
1. Définition
Un programme ne se déroule pas toujours comme prévu.
Plusieurs cas d’erreurs peuvent venir perturber son bon
déroulement: division par zéro, dépassement des bornes d’un
tableau, fichier inexistant, …
Une exception est une interruption de l’exécution d’un
programme suite à une erreur. Par exemple, une division par zéro
provoque une exception de type ArithmeticException.
Les exceptions en java sont des instances des sous classes des
classes:
- [Link] (pour des erreurs graves, qui devront
généralement conduire à l’arrêt du programme)
- [Link] (pour des événements inattendus, qui
seront souvent traités de sorte qu’elle ne provoque pas l’arrêt du
programme) 3
Prof: R. EL AYACHI
2. Hiérarchie des exceptions
Les exceptions en JAVA sont considérées comme des objets
Throwable
Error
Exception RuntimeException ArithmeticExcepetion
ArrayIndexOutOfBoundExcepetion
IllegalArgumentException
…
IOExcepetion FileNotFoundException
… 4
Prof: R. EL AYACHI
2. Hiérarchie des exceptions
Les différences entre Exception et Error:
Exception Error
En relation avec l’application En relation avec
l’environnement
[Link] [Link]
Peut être récupérée Ne peut pas être récupérée
Lancement d’une exception et Arrêt du programme de façon
le traitement à l‘aide du bloc anormale
try/catch
5
Prof: R. EL AYACHI
2. Hiérarchie des exceptions
Exemple1:
public class Division_Zero{
public static void main(String [] args){
int a=3,b=0;
[Link](‘’Résultat de la division: ’’+a/b);
}
Une exception de type : ArithmeticException
6
Prof: R. EL AYACHI
2. Hiérarchie des exceptions
Exemple2:
public class Depassement_Capacité{
public static void main(String [] args){
int [] tab = new int[5];
for(int i=0;i<=5;i++) tab[i]=0;
}
Une exception de type : ArrayIndexOutOfBoundsException
7
Prof: R. EL AYACHI
3. Quelques classes d’exception
Exception Type d’exception
IOException Entrée Sortie (Exemple: lecture d’un
fichier inexistant )
ArithmeticException Arithmétique (Exemple: division par
zéro)
ArrayIndexOutOfBoundsException Dépassement des bornes d’un
tableau
NumberFormatException Format du nombre n’est pas
respecté (Exemple: un int
représenté en float)
OutOfMemoryException Dépassement de mémoire
8
Pof: R. EL AYACHI
4. Attraper une exception
1. try et catch:
Le mot clé try permet de spécifier un bloc de code sur lequel on s’attend
qu’une exception soit levée (possibilité d’avoir une erreur).
Le mot clé catch sert à spécifier le code à exécuter pour une exception
donnée. Les blocs try et catch sont utilisés comme suit:
try
{
//zone contenant des instructions pouvant générer des
erreurs
}
catch (NomException e)
{
//Traitement à faire dans le cas de l’exception e
}
9
Prof: R. EL AYACHI
4. Attraper une exception
Exemple3:
public class Division_Zero{
public static void main(String [] args){
int a=3,b=0;
try{
[Link](‘’Résultat de la division: ’’+a/b);
}
catch(ArithmeticException e){
[Link](‘’Une exception s’est produite ‘’);
}
[Link](‘’La suite du programme ‘’);
}
10
Prof: R. EL AYACHI
4. Attraper une exception
Exemple4:
public class IOException_Test{
public static void main(String [] args){
String ch;
BufferedReader clav = new BufferedReader(new InputStreamReader([Link]));
try{
[Link](‘’Entrer une information: ’’); ch = [Link]();
}
catch(EXCeption e){
[Link](‘’Une exception s’est produite ‘’);
}
[Link](‘’L’information saisie: ‘’+ch);
}
11
Prof: R. EL AYACHI
4. Attraper une exception
2. throws:
Une méthode susceptible de lancer une exception sans l’attraper
doit l’indiquer dans son en-tête par le mot clé throws.
Ce mot clé permet d’avertir le système qu’une certaine catégorie
d’exception ne seront pas traitées.
Syntaxe:
En-tête méthode throws ClasseException
Exemple:
void fonction(…) throws IOException{
…}
12
Prof: R. EL AYACHI
4. Attraper une exception
Exemple5:
public class IOException_Test{
public static void main(String [] args) throws IOException{
String ch;
BufferedReader clav = new BufferedReader(new InputStreamReader([Link]));
[Link](‘’Entrer une information: ’’);
ch = [Link]();
[Link](‘’L’information saisie: ‘’+ch);
}
13
Prof: R. EL AYACHI
4. Attraper une exception
3. finally:
Un bloc finally est un bloc d’intsructions précédé du mot clé finally.
Ce bloc sera toujours exécuté après le traitement d’exception. Il est
en général utilisé pour fermer des fichiers, libérer des ressources, …
Un bloc finally suit un bloc try ou un bloc catch.
14
Pof: R. EL AYACHI
4. Attraper une exception
Exemple6:
public class IOException_Test{
public static void main(String [] args){
int a=3,b=0;
try{
[Link](‘’Résultat de la division: ’’+a/b);
}
catch(AxceptionException e){
[Link](‘’Une exception s’est produite ‘’);
}
finally {
[Link](‘’Bloc finally ‘’);
}
}
15
Prof: R. EL AYACHI