According to this site it is perfectly usable to throw a string or integer. I find this to be pretty clean and easy to understand. What are the downsides to throw "description of what happened"
rather than throw std::runtime_error("description of what happened")
?
That site is stupid, and teaches bad design.
If you throw int
or char*
, then you will have to catch it using int
or char*
only. You may qualify it with const
.
If you throw std::runtime_error
, then you can catch it using std::runtime_error const &
, or its base class std::exception const &
.
So what is good about it?
The good about it is that if you throw an exception using a class which is ultimately derived from std::exception
, then you can write just ONE catch
block which accepts the exception as std::exception const&
, irrespective of which derived class is used to throw exception.
Here is one example:
void f(A & a)
{
if ( !check_arg(a) )
{
throw std::invalid_argument("invalid argument");
}
else if ( !check_size(a) )
{
throw std::length_error("invalid length");
}
//code
if(someCondition)
{
//assume your_own_defined_exception's ultimate base is std::exception
throw your_own_defined_exception("condition unsatisfied");
}
//...
}
Now the interesting part:
try
{
f(a); //it can throw exception of at least 3 types!
}
catch(std::exception const &e) //all types can be caught by just one catch!
{
//handle this case
}
The good is that you are not required to write three catch
blocks just because f()
could throw three different types of exception. You may write more than one catch
to handle them differently if that benefits you in some way. But the point to be noted here is: that is not a requirement!
In short, you can take advantage of the class hierarchy.
If you make it a rule in your code to throw exceptions only derived from std::exception then catching them is easier. In other words you can just have a single catch clause on std::exception:
catch (std::exception& e)
{
log_message(e);
throw;
}
But if you don't follow this rule then you end up having to write catch clauses when you don't have to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With