#include#include #include int main() { try { double x = -1.0; double y = std::sqrt(x); if(std::isnan(y)){ throw std::domain_error("Argument to square root must be non-negative."); } std::cout << "The square root of " << x << " is " << y << std::endl; } catch(const std::domain_error& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }
#includeThis example defines a function called divide that returns the result of dividing two integers. If the second argument is zero, it throws a std::domain_error with the message "Cannot divide by zero." The function is called with a zero as the second argument, resulting in an exception being thrown. The error is caught in a try-catch block and printed to the console. The std::domain_error class is part of the C++ Standard Library and can be used by including the#include int divide(int x, int y) { if (y == 0) { throw std::domain_error("Cannot divide by zero."); } return x / y; } int main() { try { int x = 10; int y = 0; int z = divide(x, y); std::cout << x << " / " << y << " = " << z << std::endl; } catch(const std::domain_error& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }