Home > Articles > Programming > Java

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

Do Something with the Exception

This can never be stressed enough. Always do something with the exception. Never simply catch the exception and ignore it. Even if you know that it can never ever happen, log the exception. Murphy has a wonderful way of making the impossible possible. I often see the following code:

try {
 Thread.sleep(1000);
} catch (InterruptedException e) {}

If this situation ever occurred, the programmer or maintainer would not know about it. The sleep would be cut short and program execution would resume as if everything were normal. The programmer would not know that some outside situation has caused this block to process abnormally.

If you need to interrupt the sleep yourself and doing so represents normal program flow, then flag it so that if an abnormal interruption occurs, you are made aware of it. Consider this change:

boolean interrupt = false;

public void interruptSleep() {
  interrupt = true;
  interrupt();
}

public void run() {
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   if (!interrupt) {
    log.warning("Unexpected interruption", e);
   }
  }
}

Another point to be made in this example—dump the stack trace when an exception occurs. If you will catch the exception, dump its stack, which will make debugging the issue much easier. Simply printing a message to the logs stating that an error occurred does not give you any history on the error. If there are variables involved in the exception, print them out also. It will save you many hours of debugging and avoid unnecessary trips to the debugger tool.

  • + Share This
  • 🔖 Save To Your Account