beginnerFree

Custom Exceptions

Extend Exception - domain-specific errors

Custom Exceptions

Custom exceptions make error handling expressive. Extend Exception for checked, RuntimeException for unchecked.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 2:20

The Big Picture

Custom exceptions define application-specific errors with meaningful names like InvalidOrderException.

  • Extend Exception (checked) or RuntimeException (unchecked)
  • Add fields for error context (error code, user ID)
  • Improves code clarity and targeted handling

Better than generic exceptions for debugging and logging.

How It Works

Declare a class extending the appropriate exception type:

  • class OrderException extends RuntimeException
  • Provide constructors: message, cause, both
  • Add custom fields with getters for context
  • Throw: throw new OrderException("msg", id)
  • Catch specifically: catch (OrderException e)

In the Java Landscape

Modern trend favors unchecked (RuntimeException) subclasses.

  • Spring uses unchecked DataAccessException hierarchy
  • Checked exceptions for recoverable external failures
  • Java 14+ records can't extend exceptions
  • Builder pattern for complex exceptions with many fields
  • Exception hierarchies group related error types

Pitfalls and Best Practices

  • Name with Exception suffix: PaymentFailedException
  • Forward message/cause to super(...)
  • Include root cause: super(message, cause)
  • Don't create too many - group related errors
  • Override toString() only for deliberate diagnostic formatting
  • Document with Javadoc @throws on throwing methods
#java#exceptions#oop