簡體   English   中英

Java 中的自定義異常與外部消息

[英]Custom exception in Java with external message

我們剛從大學的 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;
        }
    }
} 

這里的問題是您正在調用超類的構造函數,這必須在其他任何事情之前完成。

因此,您無法訪問message方法中的b等字段,因為它們尚未設置。

將構造函數的第一行更改為

super(message(b));

message方法

private static String message(boolean b) 

這將使消息方法與值的本地副本一起工作,該值稍后將分配給 class 字段。

首先,您不應該在 static 方法中使用類的參數; 您必須通過方法的參數委托它。 然后你會得到一個非常有效的解決方案。

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: ";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM