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
extendsIllegalArgumentException
, which extendsRuntimeException
. Recall that an instance of a subclass ofRuntimeException
is unchecked. Therefore an instance ofWrongNumberOfRowsException
is an unchecked exception.