Create Class DivideByZeroException - C++ Class

C++ examples for Class:Exception Class

Description

Create Class DivideByZeroException

Demo Code

#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 &divideByZeroException) {
            std::cout << "Exception occured: " << divideByZeroException.what()
                      << std::endl;
        }
        std::cout << "\nEnter two integers (end-of-file to end): ";
    }
    std::cout << std::endl;

    return 0;
}

Result


Related Tutorials