// Throw a string:
double safesqrt(double x) {
if (x<0)
throw string(
"x must be non-negative, but it is "
+to_string(x));
return std::sqrt(x);
}
int main() {
cout << "std::sqrt(-4) = " << std::sqrt(-4) << endl;
try {
cout << "safesqrt(-4) = " << safesqrt(-4) << endl;
}catch (string message) {
cout << " caught exception: " << message << endl;
}
cout << safesqrt(-9) << endl; // uncaught exception
cout << "Program finished successfully" << endl;
}
std::sqrt(-4) = nan
safesqrt(-4) = caught exception: x must be non-negative, but it is -4.000000
terminate called after throwing an instance of 'std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<
char> >'