I'm struggling figuring out something about checked Exception in Java. What I've learned (I may be wrong) is that if you throw a checked Exception you have two options.
- you have to catch it with try catch block
- you delegate the caller with the keyword throws
In the code down below I'm going with the first option, I'm trying to catch the exception in the Main class but I get the "exception PersonaException is never thrown in body of corresponding try statement" as if I never try to catch it. What am I missing?
public class Main{
public static void main(String args[]){
Persona p = new Persona("Michele", "Bianchi");
Scanner s = new Scanner(System.in);
System.out.println("Inserisci un numero di telefono: ");
String tel = s.nextLine();
try{
p.setTel(tel);
}
catch(PersonaException e){
System.out.println(e.toString());
}
System.out.println("Ciao");
System.out.println(p.toString());
}
}
public class Persona{
private String nome;
private String cognome;
private String tel;
public Persona(String nome, String cognome){
this.nome = nome;
this.cognome = cognome;
}
public void setTel(String tel){
if(tel.length()!=10){
throw new PersonaException("Il numero di telefono è errato");
}
else
this.tel = tel;
}
public String getTel(){
return tel;
}
public String toString(){
return nome+" "+cognome+": "+tel;
}
}
public class PersonaException extends Exception{
public PersonaException(String msg){
super(msg);
}
}