Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Exception Text

Make sure that the messages contained inside your exceptions are meaningful. If the exception was caused due to variables, include the value of those variables in the message text. Nothing is harder to debug then the following:

int result = doSomething();
switch (result) {
  case RIGHT_ANSWER:
   doSomethingElse();
  case WRONG_ANSWER:
   handleWrongAnswer();
  default:
   throw new Exception();
}

At the time you might be thinking that you will capture the exception up above and you know exactly what it means, but at some point in the future, a maintainer of this code will be using your name in vain. Avoid this problem by simply including a useful message in the exception that explains what happened:

int result = doSomething();
switch (result) {
  case RIGHT_ANSWER:
   doSomethingElse();
  case WRONG_ANSWER:
   handleWrongAnswer();
  default:
   throw new Exception("Invalid response from doSomething: " + result);
}

Including the values that lead to the exception in the exception message will make it very clear what went wrong.

  • + Share This
  • 🔖 Save To Your Account