我們剛從大學 Java 的例外開始,我在這個任務上坐了很長時間,但我仍然無法走得更遠。
任務是根據建構式中的引數自定義帶有訊息的例外。我的想法是為訊息撰寫一個額外的方法,但我很難訪問引數中的變數
這是我到目前為止所擁有的
import java.util.Calendar;
public class BadUpdateTimeException extends Exception{
private final boolean b;
private final Calendar cal;
public BadUpdateTimeException(Calendar cal, boolean b) {
super(message());
this.b = b;
this.cal = cal;
}
private static String message() {
if(b == true) {
String s = "Update time is earlier than the last update: ";
return s;
}else {
String s = "Update time is in the future: ";
return s;
}
}
}
uj5u.com熱心網友回復:
這里的問題是您正在呼叫超類的建構式,這必須在其他任何事情之前完成。
因此,你不能訪問領域,如b在你的message方法,因為它們沒有被設定。
將建構式的第一行更改為
super(message(b));
和message方法
private static String message(boolean b)
這將使訊息方法與稍后將分配給類欄位的值的本地副本一起使用。
uj5u.com熱心網友回復:
首先,你不應該在靜態方法中使用類的引數;您必須通過方法的引數委托它。然后你會得到一個非常有效的解決方案。
public class BadUpdateTimeException extends Exception{
public BadUpdateTimeException(Calendar cal, boolean b) {
super(createMessage(cal, b));
}
private static String createMessage(Calendar cal, boolean b) {
if (b)
return "Update time is earlier than the last update: ";
return "Update time is in the future: ";
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/406208.html
標籤:
