Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is throwing a non exception considered bad design?

Tags:

c++

exception

I have some code to sort a vector of objects. If any of the objects is invalid I want to stop sorting immediately and report an error. In the error, I want to include the description of an invalid object (no matter which one if there are many).

This is my code (not complete, but I hope you can follow me):

int sortProc(const Bulk & b1, const Bulk & b2) {
    if (!b1.isValid()) throw b1;
    if (!b2.isValid()) throw b2;
    return b1.compareTo(b2);
}

vector<Bulk> * items = getItems();
try {
    sort(items->begin(), items->end(), sortProc);
} catch (const Bulk & item) {
    cout << "Cannot sort item: " << item.description();
}

Now, I'm a bit unsure of my code because I've heard that all exceptions should subclass the exception class and it's considered bad practice to throw objects that are not instances of exception, but I don't really understand why. My code above works, is anything wrong with it? This is a serious question, so if you see any problems I'd be glad to know. I'm not looking for moral concerns.

like image 550
TyMarin Avatar asked Nov 22 '25 11:11

TyMarin


1 Answers

I'm not looking for moral concerns.

You can't ask a style question then ban all answers based on "moral concerns", if you expect to figure it out.

Some people think that throwing only objects of types deriving std::exception provides consistency of interface, since you can invoke .what() on all of them and catch them all together at the top level of your program. You can also guarantee that other translation units — those who have never heard of your class Bulk — will be able to catch the exception if they want to (if only as a std::exception).

  • Is your program wrong? No.

  • Does it work? Yes, of course it does.

But sometimes simply "working" is not considered enough and we like to be a little more tidy about things.

That's really it...

like image 54
Lightness Races in Orbit Avatar answered Nov 25 '25 01:11

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!