Dont understand the exception handeling in the case of changing interfaces as mentioned in Refactoring book by Fowler

I'm reading the Fowler book on Refactoring. In chapter 2 in the changing interfaces section. I don't understand this passage:

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.

Could someone explain with an example? Thanks a ton!

Jon Skeet
people
quotationmark

Suppose you currently have:

public interface Foo {
    void bar();
}

You cannot later evolve this to:

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

(where SomeException is a checked exception) because code that previously called bar() won't be catching SomeException... it will fail to compile after the change. The suggested fix is to introduce a new method instead:

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

... although then any implementations of Foo become invalid because they don't declare barWithException().

The other alternative suggested is to make SomeException an unchecked exception, warning users that it might become checked later.

people

See more on this question at Stackoverflow