Académique Documents
Professionnel Documents
Culture Documents
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 :
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