简体   繁体   中英

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.

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.

Change the first line of your constructor to

super(message(b));

and the message method to

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.

First of all, you should not use class' parameters in the static method; 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: ";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM