C ++ exceptions: why use or extend std :: exception?

According to this site, it is entirely possible to use a string or an integer. I think this is pretty clean and easy to understand. What are the cons throw "description of what happened", not throw std::runtime_error("description of what happened")?

+5
source share
4 answers

This site is stupid and teaches poor design.

If you choose intor char*, you only have to catch it with intor char*. You can qualify it with const.

If you throw it away std::runtime_error, you can catch it with std::runtime_error const &or with its base class std::exception const &.

So what is good?

, , , std::exception, ONE catch, std::exception const&, .

:

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 ultimate base is std::exception
          throw your_own_defined_exception("condition unsatisfied");                         
    }
    //...

}

:

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
}

, catch , f() . catch, -, - . : !

, .

+14

, , std:: exception, . , catch std:: exception:

catch (std::exception& e)
{
    log_message(e);
    throw;
}

, catch, .

+2

, , , , . const std::exception&, const char*, , .

, , . , std::exception const char*, , . .

+1

-

If you throw an int or string, and you want to catch one specific error, you cannot. You have to catch all the "int" exceptions, and then compare the ones you want to catch, and then drop all that you are not ready to handle. If you inherit an exception, you can catch the specific exception that you want to handle, and still have the advantage that you can just catch std :: exception if you want to handle all of them.

+1
source

All Articles