Vous êtes sur la page 1sur 2

Support de Cours : Programmation Orientée Objet P a g e | 75

Syntaxe :

try {
// scenario normal
} catch (TypeException1 e1) {
// bloc Catch 1
} catch (TypeException2 e2) {
// bloc Catch 2
} catch (TypeException3 e3) {
// bloc Catch 3
}finally {
// Le bloc finally s'exécute toujours.
}
Exemple :

public class ExcepTest {

public static void main(String args[]) {


int t[] = new int[2];
try {
System.out.println("Accès au 3ème élément :" + t[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
t[0] = 6;
System.out.println("Premier élément de valeur: " + t[0]);
System.out.println("L’instruction finally est exécutée");
}
}
}
Exercice d’application
1) Ecrire un programme java qui permet de calculer la division de deux valeurs entières
saisies au clavier.

2) On suppose qu’il y’en a pas une condition qui traitera la division par zéro, rajouter au
code précédent le traitement de l’exception ArithmeticException (utiliser pour
cela : try .. catch).

3) Créer une classe d’exception et réécrire le code qui permet de lever l’exception lors
d’une division par zéro (utiliser dans ce cas throw)

RIADH BOUSLIMI
RIADH BOUSLIMI
1)
import java.util.Scanner;
public class test {
public static void main(String[] args){
Scanner clavier = new Scanner(System.in);
System.out.print("Entre x :");
int x = clavier.nextInt();
System.out.print("Entre x :");
int y = clavier.nextInt();
System.out.println("La division égale :" + (x/y));
}
}
2)
import java.util.Scanner;
public class test {
public static void main(String[] args){
Scanner clavier = new Scanner(System.in);
try{
System.out.print("Entre x :");
int x = clavier.nextInt();
System.out.print("Entre x :");
int y = clavier.nextInt();
System.out.println("La division égale :" + (x/y));
}catch(NumberFormatException ex1){
System.err.println(ex1.getMessage());
}catch(ArithmeticException ex2){
System.err.println(ex2.getMessage());
}
}
}
3)
//MonException.java
public class MonException extends Exception {
private String msg;
public MonException(String msg){
super(msg);
}
public String getMsg(){
return msg;
}
}
//test.java
import java.util.Scanner;
public class test {
public static void main(String[] args) throws MonException{
Scanner clavier = new Scanner(System.in);
System.out.print("Entre x :");
int x = clavier.nextInt();
System.out.print("Entre x :");
int y = clavier.nextInt();
if (y==0)
throw new MonException("Division par zéro");
System.out.println("La division égale :" + (x/y));
}
}
P a g e | 76 Support de Cours : Programmation Orientée Objet

Vous aimerez peut-être aussi