La gestion de plusieurs exceptions
Bonjour,
J'ai crée deux classes NomVilleException et NombreHabitantExeption pour gérer deux exceptions (si l'utilisateur crée une instance de Ville avec un nom inférieur à 3 lettres/si l'utilisateur crée une instance de Ville avec un nombre d'habitants négatif), lorsque j'instancie un objet Ville avec un nombre d'habitants négatif et un nom inférieur à trois lettres je n'ai qu'une seule exception de capturé :
Code:
1 2 3 4 5 6 7 8 9 10 11
| public class NombreHabitantExeption extends Exception {
public NombreHabitantExeption() {
System.out.println("Nombre d'habitants négatif !!!");
}
public NombreHabitantExeption(int nbr) {
System.out.println("Nombre d'habitants négatif !!!"+nbr);
}
} |
Code:
1 2 3 4 5 6
| public class NomVilleException extends Exception {
public NomVilleException() {
System.out.println("le nom de la ville est inférieur à 3 caractères");
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class Ville {
private String nomVille;
private String nomPays;
private int nbreHabitants;
private char categorie;
public Ville(){
System.out.println("Création d'une ville !");
nomVille = "Inconnu";
nomPays = "Inconnu";
nbreHabitants = 0;
this.setCategorie();
}
public Ville(String pNom, int pNbre, String pPays) throws NombreHabitantExeption, NomVilleException
{
if(pNbre < 0)
throw new NombreHabitantExeption(pNbre);
if(pNom.length() < 3)
throw new NomVilleException();
else
{
nomVille = pNom;
nomPays = pPays;
nbreHabitants = pNbre;
this.setCategorie();
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
public class TestException {
public static void main(String[] args) {
Ville v = null;
try {
v = new Ville("Re", -12000, "France");
}
//Gestion de l'exception sur le nombre d'habitants
catch (NombreHabitantExeption e) {}
//Gestion de l'exception sur le nom de la ville
catch(NomVilleException e2){}
}
} |
Résultat retourné : Nombre d'habitants négatif !!!-12000
Merci de votre aide.