Reputation: 409
I was wondering why, and if so, to what advantage, you would create an exception object to throw exceptions, that derives from stdexcept header, such as an exception object that derives from runtime_error. The only thing i can really find on why you would do this, is so you can access the virtual function 'what' to obtain an appropriate error message. But can't you just pass the error message into runtime_error as an argument, and access 'what' anyway?
class divide_by_zero : public runtime_error
{
public:
divide_by_zero()
:runtime_error( "this is a runtime error" ) {};
}
if( ... )
{
throw divide_by_zero();
}
How is it any different than just doing something like...
if( ... )
{
throw std::runtime_error( "this is a runtime error" );
}
try
{
...
}
catch( std::runtime_error& e )
{
std::cerr << e.what()
<< std::endl;
}
Upvotes: 1
Views: 218
Reputation: 106196
Retired Ninja commented "You can catch the derived exception without catching all runtime_error
exceptions.", and that's a key point. Your code might expect your divide_by_zero
and want to ignore or log it, but not want a runtime_error
thrown by say std::locale::locale
to be hidden by that.
Further, note that if you used the same class and relied on comparisons of the what()
-returned text, that would be very "fragile" as the throwing site generally expects to be able to reword the messages at whim to improve their clarity and utility. It's likely slower too.
If you use your own class, you can more easily enrich it later in a structured way, perhaps putting some details of the error, or processing underway when the error was encountered, into other variables that can be easily and reliably used. That can be contrasted with a post-facto move to embed new data in the text, which can confound current code with expectations about the message "style" and likely length (e.g. it might "blow out" a dialog box so it won't fit on screen cleanly), and having the text need to either become rigidly structured (e.g. moved to XML) or error-prone to parse....
Upvotes: 2
Reputation: 837
It allows you to craft exceptions that are tailored to your specific API, while also adhering to the basic contract provided by std::exception
. This allows you to provide a catch-all exception handler in main()
or at the entry point to a DLL or .so file to prevent exceptions from leaking out of your program.
Upvotes: 0