Custom exceptions

Custom exception #

Custom exceptions can be created by extending one of Java’s native exception types. For instance:

public class WrongNumberOfRowsException extends IllegalArgumentException {

    public WrongNumberOfRowsException(int numberOfRows) {
        super("This sudoku grid has " + numberOfRows + " rows, whereas it should have 9").
    }
}

A custom exception can be thrown like a regular one:

if(sudokuGrid.length != 9){
    throw new WrongNumberOfRowsException(sudokuGrid.length);
}

Observation. In this example, WrongNumberOfRowsException extends IllegalArgumentException, which extends RuntimeException. Recall that an instance of a subclass of RuntimeException is unchecked. Therefore an instance of WrongNumberOfRowsException is an unchecked exception.