I created a general class that accepts a string when it is constructed, and it spits out that string when a user calls what(). This is all it does; on throw, it returns the initializing string.
class Exception_As {
private:
std::string message
public:
Exception_As(const std::string& message) { // constructor
this->message ="EXCEPTION: " +message;
}
virtual const char* what() const throw() {
return message.c_str();
}
}
How I use my custom exception class:
bool check_range(
const std::vector<std::string>& list,
const unsigned& idx_start, // where to start checking
const unsigned& idx_end, // where to stop checking
const std::string& key
) {
if ( idx_start > idx_end ) {
throw Exception_As("check_range: start index > end index: now fix it! :D");
}
... rest of code
} // end of check_range
How a user would use check_range:
// some other user code using my check_range
void main() {
try {
... set up variables
my_hero_qualified = check_range(semi_finalists, third_place, first_place, my_hero);
...rest of code
}
catch (const Exception_As& e) {
std::cout << e.what() << std::endl;
}
}
If the try/catch was not there, it would abort the program because of the thrown Exception_As. If it was there, the user would be notified that "check_range: start index > end index: now fix it! :D". For me, sure beats writing tons of BadEvent1Exception, BadEvent2Exception, etc classes.
I can see I'm being lazy with this method, and yeah, I can't do anything fancy like modify values based on exceptions or morph an object's state; but if you just entered unexpected territory, who knows if you're handling it correctly? May as well just end it so you can fix what's up and develop properly.
So, question: if all exceptions do is break the program on unexpected circumstances, won't a single exception class that returns the problem be enough?
...Or should exceptions be doing other things anyway? If not, why create so many classes of Exceptions that have different names, sure, but from what I've seen, only report that something went wrong.