简体   繁体   English

Java 中的自定义异常与外部消息

[英]Custom exception in Java with external message

We just started with exceptions in Java in University and I am sitting on this task for quite a time and I still couldn't get much further.我们刚从大学的 Java 中的异常开始,我在这个任务上坐了很长时间,但我仍然无法走得更远。

The task is to customize an exception with a message depending on the parameters in the constructor.任务是根据构造函数中的参数自定义带有消息的异常。 My idea was to write an extra method for the message but I am struggling to access the variables in the parameter我的想法是为消息编写一个额外的方法,但我很难访问参数中的变量

Here is what I have so far这是我到目前为止所拥有的

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

The problem here is that you are calling the superclass's constructor, which has to be done before anything else.这里的问题是您正在调用超类的构造函数,这必须在其他任何事情之前完成。

Thus, you cannot access fields such as b in your message method, since they are not set yet.因此,您无法访问message方法中的b等字段,因为它们尚未设置。

Change the first line of your constructor to将构造函数的第一行更改为

super(message(b));

and the message method tomessage方法

private static String message(boolean b) 

This will make the message method work with a local copy of the value which will later be assigned to the class field.这将使消息方法与值的本地副本一起工作,该值稍后将分配给 class 字段。

First of all, you should not use class' parameters in the static method;首先,您不应该在 static 方法中使用类的参数; you have to delegate it via the method's parameter.您必须通过方法的参数委托它。 Then you get a pretty working solution.然后你会得到一个非常有效的解决方案。

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