Aer*_*rus 3 java inheritance try-catch
我们正在尝试实现某种Chess游戏,我们已经使用构造函数定义了一个抽象类Piece:
public Piece(String name) throws EmptyStringException{
if(name.length()<=0)
throw new EmptyStringException();
pieceName = name;
}
Run Code Online (Sandbox Code Playgroud)
扩展类可能如下所示:
public King(boolean white) throws EmptyStringException{
super("King", white);
}
Run Code Online (Sandbox Code Playgroud)
这里的'问题'是,如果我想创建一个新的King作品我必须写:
try {
Piece king = new King(true);
} catch(EmptyStringException e){
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
而不是更简单:
Piece king = new King(true);
Run Code Online (Sandbox Code Playgroud)
所以,即使我根本无法创建EmptyStringException,我仍然需要尝试/捕获异常.
我怎么能解决这个问题所以我仍然可以在Piece中抛出EmptyStringException,但是每次我需要创建一个新的国际象棋时都不必尝试/ catch?
使用运行时异常:
public class EmptyStringException extends RuntimeException
Run Code Online (Sandbox Code Playgroud)
而不是平原Exception.您仍然可以在方法声明中记录异常,但不是强制客户端代码处理异常.