gpt4 book ai didi

java - 不了解 Fowler 的《重构》书中提到的更改接口(interface)时的异常处理

转载 作者:行者123 更新时间:2023-12-02 05:57:53 25 4
gpt4 key购买 nike

我正在阅读 Fowler 的有关重构的书。在第 2 章的更改接口(interface)部分。我不明白这段话:

There is one particular area with problems in changing interfaces in Java: adding an exception to the throws clause. This is not a change in signature, so you cannot use delegation to cover it. The compiler will not let it compile, however. It is tough to deal with this problem. You can choose a new name for the method, let the old method call it, and convert the checked into an unchecked exception. You can also throw an unchecked exception, although then you lose the checking ability. When you do this, you can alert your callers that the exception will become a checked exception at a future date. They then have some time to put the handlers into their code. For this reason I prefer to define a superclass exception for a whole package (such as SQLException for java.sql) and ensure that public methods only declare this exception in their throws clause. That way I can define subclass exceptions if I want to, but this won't affect a caller who knows only about the general case.

有人可以举例说明吗?非常感谢!

最佳答案

假设您目前有:

public interface Foo {
void bar();
}

您以后不能将其发展为:

public interface Foo {
void bar() throws SomeException;
}

(其中 SomeException 是一个已检查异常),因为之前调用 bar() 的代码不会捕获 SomeException...修改后会编译失败。建议的修复方法是引入一种新方法:

public interface Foo {
void bar();
var barWithException() throws SomeException;
}

...尽管 Foo 的任何实现都会变得无效,因为它们没有声明 barWithException()

建议的另一种替代方法是使 SomeException 成为未经检查的异常,警告用户稍后可能会检查它。

关于java - 不了解 Fowler 的《重构》书中提到的更改接口(interface)时的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22918175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com