Nicholas
Nicholas

Reputation: 509

Is there a convention for Java exception messages?

I have been trying to throw exceptions with more information coming with it. I made it multiple lines since I want to make it verbose and help debugging.

throw new RuntimeException("Something failed.\n" + 
    "Please provide another dependency on this class\n\n" + 
    "  MyClass object = new MyClass(depdencyA, dependencyB)");

However should I be doing it? Seems like many exceptions are one-liners, but I feel like its not verbose enough.

FYI, I am writing Gradle plugins, so please let me know if there are different conventions as well.

If there is one, please show me reference or documentations from authorities like Oracle.

Upvotes: 5

Views: 2670

Answers (2)

Stephen C
Stephen C

Reputation: 719376

There are no general conventions. However:

  1. Throwing a RuntimeException like that is generally a bad idea.

  2. Verbose exception messages can be overwhelming if they are directed at an ordinary user.

  3. There are no guarantees that markup (like line breaks, tabs, etc) embedded in an exception message will be handled sensibly. (For a start, you cannot predict the character width of the window in which the message will be displayed, and (even) whether a fixed-width font will be used.)

  4. Internationalization ....

For the Gradle case, you can (should) check what other plugins do, and also see how Gradle handles multi-line exception messages.


Another way to deal with providing extra detail for diagnosis is to use the application's Logger to log an INFO or DEBUG event with the details ... before you throw the exception.

Upvotes: 1

Thomas Kläger
Thomas Kläger

Reputation: 21630

Exceptions (and exception messages) should be as specific and concise as possible.

They should give enough information to pinpoint the problem and inform the user (or administrator) in how to solve the problem.

Your example fails on these points:

  1. RuntimeException is very generic - select a more specific exception type (maybe some existing exception type, maybe some exception type you create)
  2. "Something failed." is unnecessary - if everything was OK you would not throw an exception
  3. "Please provide another dependency on this class" - if your class needs a specific number of dependencies the tell the user about it: "Only 2 of 5 dependencies supplied". Or tell the user what dependency is missing: "No DataSource found"
  4. "MyClass object = new MyClass(depdencyA, dependencyB)" - this part assumes some call style on the users side. What if your constructor / method is called using reflection or through a method reference?
  5. The exact location where the exception is thrown is also included within the stack trace - do not include this information in your exception message again

Upvotes: 3

Related Questions