Java Language Custom Exceptions

Download Java Language for free


Under most circumstances, it is simpler from a code-design standpoint to use existing generic Exception classes when throwing exceptions. This is especially true if you only need the exception to carry a simple error message. In that case, RuntimeException is usually preferred, since it is not a checked Exception. Other exception classes exist for common classes of errors:

Cases where you do want to use a custom exception class include the following:

  • You are writing an API or library for use by others, and you want to allow users of your API to be able to specifically catch and handle exceptions from your API, and be able to differentiate those exceptions from other, more generic exceptions.
  • You are throwing exceptions for a specific kind of error in one part of your program, which you want to catch and handle in another part of your program, and you want to be able to differentiate these errors from other, more generic errors.

You can create your own custom exceptions by extending RuntimeException for an unchecked exception, or checked exception by extending any Exception which is not also subclass of RuntimeException, because:

Subclasses of Exception that are not also subclasses of RuntimeException are checked exceptions

public class StringTooLongException extends RuntimeException {
    // Exceptions can have methods and fields like other classes
    // those can be useful to communicate information to pieces of code catching
    // such an exception
    public final String value;
    public final int maximumLength;

    public StringTooLongException(String value, int maximumLength){
        super(String.format("String exceeds maximum Length of %s: %s", maximumLength, value));
        this.value = value;
        this.maximumLength = maximumLength;

Those can be used just as predefined exceptions:

void validateString(String value){
    if (value.length() > 30){
        throw new StringTooLongException(value, 30);

And the fields can be used where the exception is caught and handled:

void anotherMethod(String value){
    try {
    } catch(StringTooLongException e){
        System.out.println("The string '" + e.value + 
                "' was longer than the max of " + e.maximumLength );

Keep in mind that, according to Oracle's Java Documentation:

[...] If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.


Handling InterruptedException