How can I set the message on an exception in Java?

Most standard exception classes provide a constructor that takes a mesage, for example:

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

The above class simply calls its parent's constructor, which calls its parent's constructor, and so on, ultimately culminating in:

public Throwable(String message) {
    ...
}

If you create your own exception class, I think it's a good idea to following this convention.


Well, if the API offers an exception that suits your needs (IllegalArgumentException for example), just use it and pass your message in the constructor.


You can only set the message at the creation of the exception. Here is an example if you want to set it after the creation.

public class BusinessException extends RuntimeException{

    private Collection<String> messages;

    public BusinessException(String msg){
        super(msg);
    }


    public BusinessException(String msg, Exception cause){
        super(msg, cause);
    }


    public BusinessException(Collection<String> messages){
        super();
        this.messages= messages;
    }


    public BusinessException (Collection<String> messages, Exception cause){
        super(cause);
        this.messages= messages;
    }

    @Override
    public String getMessage(){
        String msg;

        if(this.messages!=null && !this.messages.isEmpty()){
            msg="[";

            for(String message : this.messages){
                msg+=message+",";
            }

            msg= StringUtils.removeEnd(msg, ",")+"]";

        }else msg= super.getMessage();

        return msg;
    }

}

Tags:

Java

Exception