I want to set a custom exception message. However, I'm unsure of how to do this. Will I need to create a custom exception class or is there an easier way of doing this?
8 Answers
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.
Comments
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;
}
}
Comments
The root Exception class accepts a String custom message, as do (as far as I can tell) all of derivative classes.
So: no, you don't need to create a custom class. One of the existing exceptions probably covers your case (read their descriptions to find out which). If none of those are really satisfactory, then you can create an extension of Exception (or RuntimeException, etc.) and maintain the custom message constructor.
Comments
Try this code:
try{
throw new Exception("Test String");
}
catch(Exception ex){
System.out.println(ex.getMessage());
}