On Tuesday, August 26, 2003, at 07:13 pm, Dain Sundstrom wrote:
-1 for the reason below and I believe this type of requirement on programmers will lead to worse exception handling. If a developer has to add a new class for every exception message, they won't throw exceptions.
Then they're very lazy developers :)
Absoultely. Being a lazy developer is great; learn to make the tools work for you. In eclipse, you can say 'throw new NonExistantException()' and then the red-squiggle underline gives you a prompt to create the class...
Leaving exception messages in the code (with or without i18n) is a code smell IMHO. Especially when often lots of useful exception details are hidden in the text message, rather than being exposed as typesafe getters.
I think it's important to treat the two points separately; non-i18n messages, and data-in-messages. It's much better (as you say) to have them stored in exception instance variables (where appropriate) and then weave them into the message later; hence the i18n messages of the form 'User %{0} logged in".
public class FooException extends Exception {
public static FooException newFailedToOpenFileException(File file) {
return new FooException("org.a.g.foo.FooException.failedToOpenFile", file);
}
public static FooException newFailedToCloseFileException(File file, int bar) {
return new FooException("org.a.g.foo.FooException.failedToCloseFile", file, bar);
}
}
Or even better:
public class FooException extends Exception {
public static void generate(File file) throws FooException {
throw new FooException("org.a.g.foo.FooException",file);
}
}-- after all, there's not (often) a point in having an exception instance without throwing it.
The main aim I'm suggesting is to save littering the code with exception message text, i18n patterns and so forth and unify their use inside the Exception classes themselves. Whether there is a nice exception hierarchy to catch exact exceptions or there are big generic exceptions that serve many different purposes (which I don't personally like), we can still easily hide the message text & i18n inside the exception classes - which will make refactoring easier down the road.
Absolutely. However, the [i18n] thread was also raised to discuss messages outside of exceptions, too -- IMHO it's become somewhat exception-focussed recently.
Alex.
