Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Solution TP Exceptions

Pr. Said Benkirane, ESTE 2022/2023

A/ TP1 : Traitement des exceptions

import java.util.InputMismatchException;
import java.util.Scanner;
public class TP1 {
public static void main(String[] args) {
try{
int a,b,c;
Scanner sc=new Scanner(System.in);

System.out.println("Donner a:");
a=sc.nextInt();
System.out.println("Donner b:");
b=sc.nextInt();
c=a/b;
System.out.println(c);
}catch(InputMismatchException e2){
System.out.println("Attention erreur de");
}
catch(ArithmeticException e1){
System.out.println("Attention division sur zéro");
System.out.println(e1.toString());
System.out.println(e1.getMessage());
e1.printStackTrace();
}
finally{
System.out.println("Traitement forcé");
}}}

B/ TP2 : Catcher Function

public class TP2 {


public String nom;
public void sePresenter(int age){

try {
if(age<0)
throw new Exception();
System.out.println("je m'appelle: "+this.nom+ " agé de: "+age);

} catch (Exception ex) {


System.out.println(ex.getMessage());
// return;
}}}

C/ TP3 : Thrower Function

public class TP2 {


public String nom;
public void sePresenter(int age) throws Exception{
if(age<0)
throw new Exception();
System.out.println("je m'appelle: "+this.nom+ " agé de: "+age);
}}

D/ TP4 : Création d’une Exception personnalisée

public class MyException extends Exception{


public MyException(){
super("Attention age negatif");
}}

You might also like