2017/12/16

Java 自訂例外處理

class MemberIDException extends Exception{
    public MemberIDException(String mID){
        super("ERROR: " + mID)
    }
    public void contactWith(){ // 自訂例外中的自訂方法
        System.out.println("Please try again.");
    }
}

public static void main(String[] args){
    try{
        checkMemberID("123456");
    }
    catch(MemberIDException e){
        tem.out.println(e.getMessage());
        e.contactWith(); // 自訂例外類別中的自訂方法
    }
}

public static void checkMemberID(String mID) throws MemberIDException{
    if(mID.length() != 5){
        throw new MemberIDException(mID); // 自訂例外
    }
}
轉載自http://jhengjyun.blogspot.tw/2010/06/java-extends.html

沒有留言:

張貼留言