繁体   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