Throws與繼承/Override
●如果父類別的method有throws Checked Exception
--遵照Method Override,一模一樣
--Override時,可不寫throws XXXException
--Override時,可丟出比父類別使用的Exception更小的Exception
--不可丟出比父類別使用的Exception更大的Exception
●如果父類別的method沒有throws exception
--Override時,不可丟出(theows) Checked Exception
--Override時,可丟出UnChecked Exception
自建例外類別(Checked Exception):
●繼承自 java.lang.Exception
●通常會寫二個Constructor
--Default Constructor
--收一個String 的 Constructor
●Sample
public class IllegalIDException extends Exception{
public IllegalIDException() {
}
public IllegalIDException(String message) {
super(message);
}
}
public class Employee {
private int Id;
public int getId() {
return Id;
}
public Employee() {
}
public Employee(int Id) {
this.Id = Id;
}
@Override
public String toString() {
return "ID:" + this.getId();
}
public void setId(int Id) throws IllegalIDException { //Checked Exception下需要寫throws
if(Id <= 0)
throw new IllegalIDException("illege ID");
this.Id = Id;
}
}
public class Test2 {
public static void main(String[] args) {
try { //Checked Exception下需要寫try-catch
Employee emp = new Employee();
emp.setId(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Out:
test2.IllegalIDException: illege ID
自建例外類別(UnChecked Exception):
●繼承自 java.lang.RuntimeException
●Sample
public class IllegalIDException extends RuntimeException{
public IllegalIDException() {
}
public IllegalIDException(String message) {
super(message);
}
}
public class Employee {
private int Id;
public int getId() {
return Id;
}
public Employee() {
}
public Employee(int Id) {
this.Id = Id;
}
@Override
public String toString() {
return "ID:" + this.getId();
}
public void setId(int Id) { //UnChecked Exception不需要寫throws
if(Id <= 0)
throw new IllegalIDException("illege ID");
this.Id = Id;
}
}
public class Test2 {
public static void main(String[] args) {
Employee emp = new Employee(); //Checked Exception下需要寫try-catch
emp.setId(0);
}
Out:
test2.IllegalIDException: illege ID
課題: 需顯示自訂的錯誤訊息。
1. IllegalNameException
2. Unchecked Exception
3. Input: Null or "" or " " or " "
public class IllegalNameException extends RuntimeException {
public IllegalNameException() {
}
public IllegalNameException(String message) {
super(message);
}
}
public class Employee {
private String Name;
public String getName() {
return Name;
}
public Employee() {
}
public Employee(String Name) {
this.Name = Name;
}
@Override
public String toString() {
return " Name:" + this.getName();
}
public void setName(String Name) {
if(Name == null || Name.trim().length() == 0) //trim() 把空白消除
throw new IllegalNameException("illege Name");
this.Name = Name;
}
}
public class Test2 {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName(null);
//emp.setName("");
//emp.setName(" ");
//emp.setName(" ");
}
}
Out:
Exception in thread "main" test2.IllegalNameException: illege Name
結論:
1.這不是唯一解法
2.若把 if(Name == null || Name.trim().length() == 0) 兩個判斷互換,在輸入null的情況下會出現 NullPointerException,這樣就不符合課題。
留言列表