I am now working on an idea to create a single catch statement and identify the validation and some run time exceptions. So I did create two custom exception classes with the virtual function for what(). The problem is that I am getting std::exception when I tried to access the virtual function.
Whenever there is an exception that occurs, I created a pointer object for the base class and an object for the custom execption class and i assigned the reference of the custom exception class object to the base class pointer and I did throw the base class pointer and tried to access it from the catch statement but I am getting std::exception as output! Help me out where I am wrong.
This is my Header File
This is my Implementation .cpp FileHTML Code:#include<iostream> #include<exception> using namespace std; class A { protected: int a,b; public: bool setdata(); virtual void calculate()=0; }; class B : public A { virtual void calculate(); }; class DivideException : public exception{ public: virtual const char * what() const throw() { return "It is a divide by zero exception\n"; } }; class InputException : public exception{ public: virtual const char * what() const throw() { return "It is an Input Exception"; } };
Here is my main.cpp file, it is quite simple.HTML Code:#include"head.h" #include<string> #include"sstream" void B :: calculate() { try{ cin>>a; if(!cin) { exception *i; //The Way I tried to access the Virtual Function InputException f; i=&f; throw i; } cin>>b; if(!cin) { exception *i; InputException f; i=&f; throw i; } if (b == 0) { exception *j; DivideException d; j=&d; throw j; } else { cout << "a / b = " << a/b << endl; } } catch( std::exception* e) { cout<<(e->what()); //No matter what Exception I throw, it keeps printing me std::exception } }
What am I doing wrong here????? Sample I/O:HTML Code:#include"head.h" int main() { A *obj; B e; obj=&e; obj->calculate(); return 0; }
1 0 std::exception
1 a std::exception
Output I am expecting: 1 0 It is a Divide by Zero Exception.
1 a It is a Input Exception




Reply With Quote
