[英]Java Checked Exception
我正在努力找出有關 Java 中已檢查異常的內容。 我學到的(我可能是錯的)是,如果你拋出一個檢查異常,你有兩個選擇。
在下面的代碼中,我將使用第一個選項,我試圖捕獲 Main 類中的異常,但我得到“異常 PersonaException 從未在相應的 try 語句主體中拋出”,就好像我從未嘗試捕獲一樣它。 我錯過了什么?
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);
}
}
您缺少的是您編寫了無效的 Java 代碼。
Java 的鏈接階段不關心任何地方的任何方法的內容。 故意地。 代碼今天以一種方式工作; 也許明天有人要你稍微改變一下,或者你需要修復一個錯誤。 因此,對您的代碼的分析是無關緊要的,一切都與簽名有關。
因此,在編譯時:
try {
bunchOfStatementsHere();
} catch (CheckedException e) { .. }
javac 查看您在該 try 塊中調用的所有事物的所有簽名,但不查看您在那里調用的所有事物的代碼。
換句話說,如果bunchOfStatementsHere
是setTel("someTel");
,java看的是setTel
方法的簽名而不是代碼體!
你的setTel
方法的簽名表明它不會拋出任何東西。 它被定義為public void setTel(String tel)
- 這部分是簽名, public void setTel(String tel)
{}
中的所有內容都是正文。
這里沒有throws
子句。
當然,這也意味着你的Persona.java
文件不能編譯——你不能throw new X();
其中 X 是一個已檢查的異常,除非你捕獲它(你沒有),或者把它放在你的throws
子句中(你沒有)。
您確實必須聲明或處理任何異常,除非它是 RuntimeException。 但您還必須在創建異常的地方執行此操作:
public void setTel(String tel) throws PersonaException{
if(tel.length()!=10){
throw new PersonaException("Il numero di telefono è errato");
}
else
this.tel = tel;
}
````
if you dont declare in the signature of setTel, you must handle it here (in a try-catch), which would of course be pointless here.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.