Home > Articles > Programming > Java

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

Use Exceptions for Exceptional Events

In this context, I define an exceptional event as anything that is outside of the expected scope. If you are verifying the results in a text field, and the text field requires only numbers, a letter is not an exceptional result. That should be expected behavior. Wrong, but expected. In this situation, it is better to return an error code instead of throwing an exception.

If the situation is completely unrecoverable, it is proper to throw an exception. What is considered unrecoverable? It naturally depends on the situation, but in some cases, disk errors or network failures would be good places for the use of an exception.

Return codes are an excellent way to avoid the use of exceptions for expected bad behavior. If the situation has more than a true/false result, consider using static final int fields to represent the results from the method. Using them allows a method a far greater response range and allows the calling method to process the results using a switch statement instead of other less-elegant branching logic.

  • + Share This
  • 🔖 Save To Your Account