Java Developer interview question

How do you design exception handling in Java?

Use exceptions for exceptional failures, preserve causes, expose domain-specific errors at boundaries, avoid catch-all swallowing, and translate once into an API or retry decision where enough context exists.

Direct answer

What a strong answer covers

How it works

Exception design decides who can act on a failure. Inside the domain, a small hierarchy of unchecked exceptions carries what went wrong and preserves the cause; checked exceptions are reserved for cases the immediate caller is expected to handle. Each layer either handles an exception with real recovery or lets it propagate, and the boundary, usually a controller advice or a job runner, translates once into a status code, an error payload, or a retry decision and logs it once with context. Resources are released with try-with-resources rather than manual finally blocks.

Example

A repository throws OrderNotFoundException extending a domain NotFoundException; the @ControllerAdvice maps NotFoundException to 404 with a stable error code while an unexpected exception becomes a 500 with a correlation ID. The service layer never catches Exception broadly, so a database connectivity error still reaches the retry logic in the job scheduler.

Common mistakes

  • Catching Exception, logging it, and continuing as if nothing happened.
  • Wrapping an exception without passing the original as the cause and losing the stack trace.
  • Using exceptions for expected control flow such as validation of every field.

A useful answer structure

Answer from your own work.

Do not memorise a script: use only examples you can explain honestly in follow-up questions.

Practise this answer with MiraHint

Open the desktop workspace and rehearse a clear answer in your own words.

Download MiraHint
Java Developer interview questions