Video in progress

Middle ☕ Core Java

How do you design your own exception hierarchy for an application?

I create a few meaningful unchecked domain exceptions (extending RuntimeException): for example "not found", "business rule violated", "conflict", "external service failed". Each one makes it clear how the caller or the global handler should react, and keeps the original cause.

📖 Answer

public abstract class AppException extends RuntimeException {
    private final String code;
    protected AppException(String code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }
    public String code() { return code; }
}

public class NotFoundException extends AppException {
    public NotFoundException(String what, Object id) {
        super("NOT_FOUND", what + " topilmadi: " + id, null);
    }
}

public class BusinessRuleException extends AppException { ... } // "Mablag' yetarli emas"
public class ExternalServiceException extends AppException { ... } // the payment provider didn't respond

A global handler turns them into HTTP statuses: NotFound becomes 404, BusinessRule 409/422, ExternalService 502/503.

The rules I follow:

  • group by reaction, not by location: classes like UserServiceException and OrderServiceException are useless;
  • don't create a separate class for every technical error: nobody remembers 40 exception classes;
  • don't lose the cause: new X("...", e);
  • provide a machine-readable code: the frontend works from the code, not the text;
  • don't put sensitive data in the messages, because they end up in logs and responses.

Don't use exceptions for ordinary control flow (for example, to exit a loop): they're expensive and make the code confusing.