C++ – try/catch open/closed principle violation

cdesign-principlesobject-oriented-design

I have three or more different custom exceptions that a class can throw and I need to use try/catch in order to discover which exception was thrown.

In my point of view this piece of code violates the Open/Closed principle, because if we look the definition we see:

"software entities (classes, modules, functions, etc.) should be open
for extension, but closed for modification"

try {
    // something that throws
} catch (const FooException& e) {
    // ...
} catch (const BarException& e) {
    // ...
} catch (const BizException& e) {
    // ...
} catch (...)
{
    // ...
}

What if I need to catch another exception? I will need to insert another catch statement, right?

Is there another way for doing this? Or the language is somehow forcing me to violate the principle?

Best Answer

That depends on how you plan to recover from these exception, meaning what code is executed in the catch statements. If it's the same for all 3 exceptions, you could create a superclass for them and catch the superclass. If your method has to throw a new exception, just make it extend the superclass and it would still be caught by the caller and would not need any changes in the client code.

Generally tough, if a method throws that many exceptions it's usually a hint that the method does to much and you might want to consider refactoring it.

If you want a more detailed answer, it would be helpfull to see a complete code listing of your method.