Skip to Content
Tech PrinciplesTechnical ResourcesApplicationError Handling

Error Handling 💥

When writing Java code, properly handling errors and exceptions is crucial for building robust applications. Here are some tips for effective error handling:

Handling Exceptions

  • Catch exceptions as close as possible to where they might be thrown. This helps isolate error handling logic and avoid catching too broad of exceptions.

  • Distinguish between lower-level application exceptions and higher-level business logic exceptions in your architecture.

  • Create custom exception classes when you need to convey specific information in an exception. But don’t go overboard creating many custom exceptions.

Anti-Patterns

  • Catching Exception or Throwable too broadly. This can catch unexpected runtime exceptions. Be as specific as possible in the exception types you catch.

  • Overusing custom exceptions without clear benefits. Custom exceptions should convey specific info.

  • Mixing multiple unrelated exception types in a single catch block. This can lead to improper error handling.

Example

public class OrderService { public void processOrder(Order order) { try { // code that could throw exceptions } catch (OrderNotFoundException e) { // handle not found error } catch (PaymentException e) { // handle payment issue } catch (ApplicationException e) { // unexpected error } } }
  • The specific exceptions are caught first, with a general ApplicationException catch at the end.
  • The handling logic is close to where errors could occur.
  • Custom exceptions convey additional information.

Consolidating business exceptions when needed

If you find yourself creating many highly specific custom exception types for a particular section of code, consider consolidating them into a broader exception class with an enum property to indicate the specific error case. This avoids an explosion of custom exceptions while still conveying the necessary information.

For example, instead of individual exceptions like:

class CustomerNotFoundException extends Exception { } class ProductNotFoundException extends Exception { } class OrderNotFoundException extends Exception { }

Create a more general with an enum like

class NotFoundException extends Exception { private NotFoundType type; public NotFoundException(NotFoundType type) { this.type = type; } public enum Type { CUSTOMER, PRODUCT, ORDER } }

Summary

Carefully handling exceptions helps surface errors clearly and enables robust error handling. Focus on handling exceptions at an appropriate level of granularity.

Last updated on