在 PasswdException 類別中定義內部類別 PasswdExceptionisnum,欲在 checkpasswd() 中拋出該內部類別實例。直接 throw new PasswdException.PasswdExceptionisnum(...) 會編譯錯誤,因非靜態內部類別實例化需外部類別實例。
// 先建立外部類別實例
PasswdException outer = new PasswdException();
// 再透過外部實例建立內部類別實例
throw outer.new PasswdExceptionisnum(passwd);
public class PasswdException extends Exception {
public PasswdException(int len) {
if (len < 6) System.out.println("密碼不能小於六位");
else if (len > 6) System.out.println("密碼不能大於六位");
}
// 內部類別建議改為 static 巢狀類別,避免需外部實例
public static class PasswdExceptionIsNum extends Exception {
public PasswdExceptionIsNum(String msg) {
super("不是數字: " + msg);
}
}
}
class Passwd {
public static boolean checkpasswd(String passwd) throws PasswdException {
if (passwd.length() != 6) {
throw new PasswdException(passwd.length());
}
try {
Integer.parseInt(passwd);
} catch (NumberFormatException e) {
// 直接拋出靜態巢狀類別實例
throw new PasswdException.PasswdExceptionIsNum(passwd);
}
return true;
}
// ... main 測試 ...
}
static(巢狀類別),即可直接 new Outer.Inner()。Exception 結尾,如 PasswordLengthException、PasswordFormatException。