Sunday, February 25, 2018

C++ program : Exception handling

#include <iostream>
#include <exception>
using namespace std;
class myexception:public exception{
                                  
                                  
 virtual const char *what() const throw(){std::cout<<"DivideByZero";return 0;}
};



class DivideByZero {
public:
    int numerator, denominator;
    DivideByZero(int a = 0, int b = 0) : numerator(a), denominator(b) {}
    int divide(int numerator, int denominator){
        if (denominator == 0) {
            throw myexception();
        }
        return numerator / denominator;
    }
};

int main() {
    DivideByZero d;
    int a, b;
    cin >> a >> b;

    try {
        d.divide(a, b);
    }

    catch (exception& e){
        cout << e.what() ;
    }
    return 0;
}

Thanks
Happy Programming !


No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows