beginnerFree
Custom Exceptions
Extend Exception - domain-specific errors

Custom exceptions make error handling expressive. Extend Exception for checked, RuntimeException for unchecked.
Watch
The narrated version of this skribble — tap play for the full-size video.
0:00 / 2:20
Deep dive
The Big Picture
Custom exceptions define application-specific errors with meaningful names like InvalidOrderException.
- Extend
Exception(checked) orRuntimeException(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
DataAccessExceptionhierarchy - 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
Exceptionsuffix: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



