Implicitly Formatted Exceptions September 16, 2008
Posted by WarpedJavaGuy in java, programming.Tags: exceptions
2 comments
It takes a lot of ugly code to create beautiful exception messages.
In Java, we write code that throws and catches exceptions a lot. The core Java exception classes provide the following two constructors for instantiating exceptions with messages:
public Throwable(String message)
public Throwable(String message, Throwable cause)
Creating nicely formatted and meaningful exception messages using these two constructors is more difficult than it should be and often involves a lot of concatenations of plain text and formatted data. These concatenated string conglomerations are so tedious to write that they deter us from good message formatting practices (let alone proper grammatical correctness). When we do put in the extra effort to get our exception messages right, our code suddenly becomes ugly and loses its elegance.
The MessageFormat class would help a lot in this regard. Using it explicitly to create exception messages can make life a little easier, but I often find myself extending exceptions to use it implicitly like this:
import java.text.MessageFormat;
public class MyException extends Exception {
public MyException(String pattern, Object... args) {
super(MessageFormat.format(pattern, args));
}
public MyException(Exception cause, String pattern, Object... args) {
super(MessageFormat.format(pattern, args), cause);
}
}
Wouldn’t it be nice if all Java exceptions had these additional constructors?
public Throwable(String pattern, Object... args)
public Throwable(Throwable cause, String pattern, Object... args)
![]()