Custom Exceptions

suggest change

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 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 {
        validateString(value);
    } 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.

More:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents