how to use Exceptions in C++ program? -
hey , trying inherit exception class , make new class called nonexistingexception: wrote following code in h file:
class nonexistingexception : public exception { public: virtual const char* what() const throw() {return "exception: not find item";} };
in code before sending function writing
try{ func(); // func function inside class } catch(nonexistingexception& e) { cout<<e.what()<<endl; } catch (exception& e) { cout<<e.what()<<endl; }
inside func throwing exception nothing catches it. in advance help.
i this:
// derive std::runtime_error rather std::exception // runtime_error's constructor can take string parameter // standard's compliant version of std::exception can not // (though compiler provide non standard constructor). // class nonexistingvehicleexception : public std::runtime_error { public: nonexistingvehicleexception() :std::runtime_error("exception: not find item") {} }; int main() { try { throw nonexistingvehicleexception(); } // prefer catch const reference. catch(nonexistingvehicleexception const& e) { std::cout << "nonexistingvehicleexception: " << e.what() << std::endl; } // try , catch exceptions catch(std::exception const& e) { std::cout << "std::exception: " << e.what() << std::endl; } // if miss ... catch left over. catch(...) { std::cout << "unknown exception: " << std::endl; // re-throw one. // not handled want make sure handled correctly // os. allow exception keep propagating. throw; // note: re-throw exceptions main // did not explicitly handle , correct. } }
Comments
Post a Comment