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);
}
}
What you're missing is that you wrote invalid java code.
Java's linking phase doesn't care about the contents of any method anywhere. Intentionally. Code works one way today; perhaps tomorrow somebody wants you to change things a bit, or you need to fix a bug. Thus, analysis of your code is irrelevant, it's all about the signatures.
Thus, when compiling:
javac looks at all signatures of all the things you invoke in that try block, but not at the code of all the things you invoke there.
In other words, if
bunchOfStatementsHereissetTel("someTel");, java looks at the signature of thesetTelmethod and not at the code body!The signature of your
setTelmethod indicates it doesn't throw anything. It's defined aspublic void setTel(String tel)- that part is the signature, all the stuff in the{}that follows is the body.No
throwsclause here.Of course, this also means your
Persona.javafile doesn't compile - you can'tthrow new X();where X is a checked exception, unless you catch it (which you don't), or put it in yourthrowsclause (which you didn't).