Exemples Java - Exception personnalisée
L'exemple suivant montre comment implémenter une exception personnalisée en héritant de Exception :
Fichier TestInput.java
class WrongInputException extends Exception { //Classe personnalisée
WrongInputException(String s) {
super(s);
}
}
class Input {
void méthode() throws WrongInputException {
throw new WrongInputException("Entrée incorrecte"); //Lancer la classe personnalisée
}
}
class TestInput {
public static void main(String[] args){
try {
new Input().méthode();
}
catch(WrongInputException wie) {
System.out.println(wie.getMessage());
}
}
}
La sortie du code ci-dessus est :
Wrong inputAutres extensions
Exemples Java