Search code examples
javaoopsoftware-designopen-closed-principle

Do checked exceptions violate the open closed principle?


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 {}

Solution

  • 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, adding a checked exception to an API method that has been "frozen" does violate the principle1. But it is the act of adding the exception that is the violation ... not the exception itself, or checked exceptions in general.


    1 - And even this is debatable. The counter is that fixing design flaws and bugs does not violate the open closed principle.