[英]Overriding method with checked exceptions
I have two classes, A and B, where B extends A. I'm having a problem where B introduces an additional feature that comes with an exception ExceptionC
that doesn't apply in any way shape or form to A, but it won't compile unless A specifies that it throws ExceptionC
. 我有两个类,即A和B,其中B扩展了A。我遇到了一个问题,即B引入了附加的功能,该异常带有异常
ExceptionC
,该异常不适用于A的任何形式或形式,但不会t编译,除非A指定throws ExceptionC
。 I understand that this is by design (because of the Liskov Substitution Principle). 我了解这是设计使然(由于Liskov替换原理)。 My question is twofold:
我的问题是双重的:
Specific situation: 具体情况:
I am writing an implementation of Ultimate Tic-Tac-Toe in Java. 我正在用Java编写Ultimate Tic-Tac-Toe的实现。 Basically take a tic-tac-toe grid and fill it with tic-tac-toe grids, like this:
基本上采用井字游戏网格,并用井字游戏网格填充它,如下所示:
| | # | | # | |
| | # | | # | |
| | # | | # | |
#################
| | # | | # | |
| | # | | # | |
| | # | | # | |
#################
| | # | | # | |
| | # | | # | |
| | # | | # | |
You start in the center, and wherever X goes in that grid, O goes in the grid corresponding to that on the larger one, so after two moves it might look like this: 您从中心开始,并且X进入该网格的任何位置,O进入与较大的网格相对应的网格,因此在两次移动之后,它看起来可能像这样:
| |O# | | # | |
| | # | | # | |
| | # | | # | |
#################
| | #X| | # | |
| | # | | # | |
| | # | | # | |
#################
| | # | | # | |
| | # | | # | |
| | # | | # | |
And if the target grid is full or has already been won, the next person can choose which grid to go in. 如果目标网格已满或已经赢得,下一个人可以选择要进入的网格。
I have two normal classes, two exception classes, and an interface. 我有两个普通类,两个异常类和一个接口。
Note that in standard tic-tac-toe, there is only one board so TargetBoardFullException is completely non-applicable. 请注意,在标准井字游戏中,只有一块板子,因此TargetBoardFullException完全不适用。
Am I doing this wrong? 我做错了吗? Should I not be using exceptions for this?
我是否应该为此使用例外?
The following code shows why Java doesn't allow changing the contract: 以下代码显示了Java不允许更改合同的原因:
class A {
public void method() {
// do something
}
}
class B extends A {
public void method() throws IOException { // <- compile error here
// do something and throw and exception
}
}
class App {
public static void main(String[] args) {
A a = new B();
a.method(); // to try or not to try, that's the question now.
}
}
Of course, it doesn't compile. 当然,它不会编译。 But if it would, would we have to catch an IOException in the main method (because it's a
B
instance) or not (because we call the method on the interface)? 但是如果可以,是否必须在main方法中捕获IOException(因为它是一个
B
实例)(不是因为我们在接口上调用该方法)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.