Do checked exceptions violate the open closed principle?

Overflow 404 :

I have two checked exceptions: TestException1 and TestException2 and the following code:

void p1() throws TestException1{
    p2();
}

void p2() throws TestException1 { 
    p3();
}

void p3() throws TestException1 {}

Does the editing of the signature of p3 as follows violate the Open-Closed principle?

void p3() throws TestException1, TestException2 {}
Stephen C :

I think I understand what you mean by your question now. (2nd attempt)

Strictly speaking, any change that you make to the source code of a class violates the "closed" part of the open closed principle. The significance of the violation depends on nature of the change.

In your example, changing the checked exceptions thrown by a public API method in Java is a significant violation. It is liable to lead to compilation errors in any method that uses the methods ... or Error subclass exceptions cause by binary compatibility problems if you don't recompile. Indeed, since p3 is called by p2 and indirectly by p1, you actually need to change more of the class to get it to compile. This may make the scope of the API change larger.

So to your question:

Do checked exceptions violate the open closed principle?

Not exactly.

Checked exceptions can be used without violating the open closed principle. However, add a checked exception to an API method that has been "frozen" does violate the principle. But it is the act of adding the exception that is the violation ... not the exception itself, or checked exceptions in general.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159957&siteId=1