Search code examples
javaexceptionconventionscustom-exceptions

Java Exceptions: Should an exception contain its message inside or take it as parameter


Whenever I need to define a custom exception, if it's message will not change depending on context, I put the message inside that exception. Like this:

public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException() {
        super("User with given name is not found!");
    }
}

Instead of this:

public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {
        super(message);
    }
}

So I don't need to provide a message each time I throw this exception, I know that the message should be same in every place.

Do you think there is a problem in my approach? Which one would you prefer, and why?


Solution

  • Why not allow the message to be supplied, but provide a default.

    public class UserNotFoundException extends RuntimeException {
    
        private static final String DEFAULT_MESSAGE = "User with given name is not found!";
    
        public UserNotFoundException() {
            this(DEFAULT_MESSAGE);
        }
    
        public UserNotFoundException(String message) {
            super(message);
        }
    }