Throwing std::string

Is there a good reason why people would throw a std::exception* instead of std::string?
1
2
3
4
5
6
7
8
9
10
void f(){
  throw std::string("Error Message");
}
int main(){
  try  {
    f();
  } catch( std::string e ) {
    std::cout << e;
  }
}



I don't like std::exception because it:
1) Is abstract so I can't throw it directly
2) Forces me to define a class child of std::exception
3) Forces me to dynamically allocate and explicitly clean up the new exception.

In a small application, I don't see any advantages over std::string. I know about std::runtime_error which deals with the issues above, but it doesn't make the use of std::exception any easier, more intuitive or less verbose than std::string.

In a larger enviornment, I use generic objects which auto-handle reporting of function names, line-numbers, OS errors, and target (console/file/nagios). Everything is done for me and so I don't even need to do any reporting in the catch() statement. In that case std::exception isn't sufficient or appropriate.
Last edited on
std::exception was never intended to be thrown. What people are expected to throw are the classes derived from std::exception:

throw std::runtime_error("this should never happen"); throw std::logic_error("A cannot be !A");
etc.

At the catch site, you can catch the specific ones first (say, runtime_errors only), and then catch them all by reference to std::exception and access that string:
1
2
3
4
} catch (const std::exception& e)
{
    std::cerr << e.what() << '\n';
}


(or, if you're using boost or C++11 and care about the error codes, you can catch them by the std::system_error& root first, and then, if you still care, catch the rest as std::exception&)
Last edited on
Topic archived. No new replies allowed.