English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Quando si legge un valore dall'utente nel costruttore o in qualsiasi metodo, è possibile utilizzare una condizione if per verificare questi valori.
Nel seguente esempio Java, abbiamo definito due classi di eccezione personalizzate per verificare il nome e l'età.
import java.util.Scanner; class NotProperAgeException extends Throwable{ NotProperAgeException(String msg){ super(msg); } } class NotProperNameException extends Throwable{ NotProperNameException(String msg){ super(msg); } } public class CustomException{ private String name; private int age; public static boolean containsAlphabet(String name) { per (int i = 0; i < name.length(); i++) { char ch = name.charAt(i); if (!(ch >= 'a' && ch <= 'z')) { return false; } } return true; } public CustomException(String name, int age){ try { if (age<0||age>125) { String msg = "Età non corretta (non tra 0 e 125)"; NotProperAgeException exAge = new NotProperAgeException(msg); throw exAge; }else if(!containsAlphabet(name)&&name!=null) { String msg = "Nome non corretto (deve contenere solo caratteri tra a e z (tutti minuscoli))"; NotProperNameException exName = new NotProperNameException(msg); throw exName; } }catch(NotProperAgeException e) { e.printStackTrace(); }catch(NotProperNameException e) { e.printStackTrace(); } this.name = name; this.age = age; } public void display(){ System.out.println("Nome dello Studente: "+this.name ); System.out.println("Età dello Studente: "+this.age ); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Inserisci il nome della persona: "); String name = sc.next(); System.out.println("Inserisci l'età della persona: "); int age = sc.nextInt(); CustomException obj = new CustomException(name, age); obj.display(); } }
Risultato di output
Inserisci il nome della persona: Krishna Inserisci l'età della persona: 136 Nome dello Studente: Krishna Età dello Studente: 136 july_set3.NotProperAgeException: età non corretta (non tra 0 e 125) at july_set3.CustomException.<init>(CustomException.java:31) at july_set3.CustomException.main(CustomException.java:56) Output2: Inserisci il nome della persona: !23Krishna Inserisci l'età della persona: 24 Nome dello Studente: !23Krishna july_set3.NotProperNameException: nome non corretto (deve contenere solo caratteri tra a e z (tutti minuscoli)) Età dello Studente: 24 at july_set3.CustomException<init>(CustomException.java:35) at july_set3.CustomException.main(CustomException.java:56)