C++ examples for Class:Exception Class
Create Class DivideByZeroException
#include <stdexcept> // stdexcept header contains runtime_error class DivideByZeroException : public std::runtime_error { public:/*from www . j a v a2 s . c o m*/ DivideByZeroException(): std::runtime_error("attempted to divide by zero") {} }; #include <iostream> double quotient(int numerator, int denominator) { if (denominator == 0) throw DivideByZeroException(); return static_cast<double>(numerator) / denominator; } int main(int argc, const char *argv[]) { int number1; int number2; double result; std::cout << "Enter two integers (end-of-file to end): "; while (std::cin >> number1 >> number2) { try { result = quotient(number1, number2); std::cout << "The quotient is: " << result << std::endl; } catch (DivideByZeroException ÷ByZeroException) { std::cout << "Exception occured: " << divideByZeroException.what() << std::endl; } std::cout << "\nEnter two integers (end-of-file to end): "; } std::cout << std::endl; return 0; }