Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have three or more different custom exceptions that a class can throw and I ne

ID: 658989 • Letter: I

Question

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?

Explanation / 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.