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.