We’re trying to implement some sort of Chess game and we have defined an abstract class Piece with constructor:
public Piece(String name) throws EmptyStringException{
if(name.length()<=0)
throw new EmptyStringException();
pieceName = name;
}
And an extending class could look like this:
public King(boolean white) throws EmptyStringException{
super("King", white);
}
The ‘problem’ here is, if i want to create a new King piece i have to write:
try {
Piece king = new King(true);
} catch(EmptyStringException e){
e.printStackTrace();
}
instead of the much simpler:
Piece king = new King(true);
So even though i simply can’t create an EmptyStringException, i still have to try/catch the exception.
How can i solve this so i can still throw the EmptyStringException in Piece, but don’t have to try/catch every time i need to create a new chesspiece ?
Use runtime exception:
instead of plain
Exception. You can still document your exception in method declaration, but you are not forcing client code to deal with the exception.