JAVA基礎--自定義異常exception
阿新 • • 發佈:2019-02-13
異常圖解
捕獲異常有三種格式:①try-catch 語句;②try-catch-finally 語句;③try-finally 語句。
如果在try 或者 catch 中存在return 語句,這時finally語句還是會執行,且在return 語句前執行,執行後再執行return。
throws 與 throw 的區別
throws 是在方法的後面丟擲異常的宣告,語法:[(修飾符)](返回值型別)(方法名)([引數列表])[throws(異常類)]{......}
public void doA(int a) throws Exception1,Exception3{......}
throw是丟擲一個異常類,語法:throw (異常物件); 如自定義異常、空指標異常等。
使用者自定義異常類,只要使用自定義異常類是Exception的子類即可,開發步驟為:
1.建立自定義異常類。繼承Exception
2.在方法中通過throw關鍵字丟擲異常物件。
使用自定義異常: a) 編寫如下異常類:空異常。年齡低異常、年齡高異常、身份證非法異常。 b) 編寫員工類: i. 有編號、姓名、年齡和身份證號等屬性; ii. 構造器1:初始化編號、姓名、年齡,如果名字為空,丟擲空異常;如果年齡小於18,丟擲年齡低異常;如果年齡高於60,丟擲年齡高異常; iii. 構造器2:初始化身份證號,使用正則表示式來匹配,如果不是合法的身份證號,丟擲身份證非法異常; c)寫一個測試類來驗證這些異常。 import java.util.regex.Pattern; public class Excep { public static void main(String[] args) { Employee em = new Employee("001", "小明", 20, "51132219941018437"); try { em.EX(); } catch (NullException e) { System.out.println(e.warnMess()); }catch(AgeLowException e){ System.out.println(e.warnMess()); }catch(AgeHighException e){ System.out.println(e.warnMess()); }catch(IdIlleagleException e){ System.out.println(e.warnMess()); } System.out.println("111"); } } class Employee{ String ID; String name; int age; String IdCard; public Employee(String id,String n,int a,String ic) { this.ID = id; this.name = n; this.age = a; this.IdCard = ic; } public void EX() throws NullException,AgeLowException,AgeHighException,IdIlleagleException{ if(this.name.isEmpty()){ throw new NullException(); } if(this.age < 18){ throw new AgeLowException(); } if(this.age > 60){ throw new AgeHighException(); } boolean control = Pattern.matches("\\d{17}[[0-9]*[a-z]*]{1}",this.IdCard); if(!control){ throw new IdIlleagleException(); } } } class NullException extends Exception{ String message; public NullException(){ message="空異常"; } public String warnMess(){ return message; } } class AgeLowException extends Exception{ String message; public AgeLowException() { message = "年齡低異常。。。"; } public String warnMess(){ return message; } } class AgeHighException extends Exception{ String message; public AgeHighException() { message = "年齡高異常。。。"; } public String warnMess(){ return message; } } class IdIlleagleException extends Exception{ public String message; public IdIlleagleException() { message="身份非法異常。。。"; } public String warnMess(){ return message; } }