Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Exceptions: Why use or extend std::exception?

Tags:

c++

exception

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")?

like image 567
Steven Lu Avatar asked Jul 02 '12 05:07

Steven Lu


2 Answers

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.

like image 188
Nawaz Avatar answered Oct 13 '22 01:10

Nawaz


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.

like image 38
sashang Avatar answered Oct 12 '22 23:10

sashang