Consider some code that can throw a checked exception (an exception of type Exception). Your code catches the exception, of course. You don't just swallow the exception either, your code reports it in some way to the user through your user interface. In a log file, perhaps, or using a GUI pop-up.
Should the text you report to the user include the message text of the exception. That is, the text provided by Throwable.getMessage() or Throwable.getLocalizedMessage()?
I think not, but it seems many disagree with me. So what have I got wrong? My argument is as follows.
- The message was created when the exception was thrown. It therefore at best can provide only very low level information, which can be inappropriate for reporting to a user.
- Philosophically, using the message seems to me against the whole point of exceptions, which is to separate the detection and initiation of error handling (the
throwpart) from completion of handling and reporting (thecatchpart). Using the message means the message must be good for reporting, which moves responsibility for reporting to the location that should be responsible for only detection and initiation. That is, I'd argue that thegetMessage()part of the design ofThrowablewas a mistake. - The message is not localised. Despite its name,
getLocalizedMessage()is not much good because you might not know what locale you want to use until youcatchthe exception (is the report to go to a system log read by your English system administrators, or is it to pop up in a window for the French user of the GUI?). - I hear that Java 7 has a much improved exception hierarchy for
IOException, enabling you to handle different kinds of I/O erors in diffferentcatchclauses, making thegetMessage()text less important. That implies even the Java designers are somewhat uncomfortable withgetMessage().
I'm not asking whether reporting the stack-trace is useful. A stack-trace is only ever going to be useful for an exception that suggests a bug. That is, for an unchecked exception. I think in such circumstances providing the low-level detail of the exception message is not just useful but mandatory. But my question deals with checked exceptions, such as file-not-found.
And I am not asking about the "best practice" for the message text.