Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Exception Handling & Custom Exceptions

How should you design a custom exception hierarchy, and what belongs in the exception itself?

Level III · MidException Handling & Custom Exceptions
Short answer

Create a small hierarchy rooted at a domain base exception (often unchecked) so callers can catch broadly or specifically, and reserve distinct types for conditions callers will actually branch on.

Explanation

The exception should carry structured context — an error code, the offending id, enough state to act on — not just a string message, so logs and API responses can be machine-readable. Avoid an explosion of one-off exception classes; prefer a few well-typed exceptions carrying fields over dozens of nearly identical types.

Common mistakes
  • Creating one custom exception per error with no hierarchy.
  • Putting sensitive data in exception messages.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Exception Handling & Custom Exceptions.

Practise free

More on Exception Handling & Custom Exceptions