c++ - Throwing exceptions error 'terminate called...' -
okay, i've been following c++ guide, , got section on exception handling. couldn't of code work - produced variation on following error;
terminate called after throwing instance of 'char const*'
where "char const*" type of whatever throwing.
i ctrl-c, ctrl-v 'ed example code guide, , ran see if error fault, or if there else going on. produced same error (above) code did.
here's code guide;
#include "math.h" // sqrt() function #include <iostream> using namespace std; // modular square root function double mysqrt(double dx) { // if user entered negative number, error condition if (dx < 0.0) throw "can not take sqrt of negative number"; // throw exception of type char* return sqrt(dx); } int main() { cout << "enter number: "; double dx; cin >> dx; try // exceptions occur within try block , route attached catch block(s) { cout << "the sqrt of " << dx << " " << mysqrt(dx) << endl; } catch (char* strexception) // catch exceptions of type char* { cerr << "error: " << strexception << endl; } }
always catch absolute const
exceptions: catch (const char const* strexception)
.
it's neither intended, nor useful put changes (write operations) them. not on possible stack local copies.
though you're doing doesn't seem idea. convention exceptions these should implement std::exception
interface, caught in canonical way. standard compliant way
class invalid_sqrt_param : public std::exception { public: virtual const char* what() const { return "can not take sqrt of negative number"; } };
double mysqrt(double dx) { // if user entered negative number, error condition if (dx < 0.0) { // throw exception of type invalid_sqrt_param throw invalid_sqrt_param(); } return sqrt(dx); }
// exceptions occur within try block // , route attached catch block(s) try { cout << "the sqrt of " << dx << " " << mysqrt(dx) << endl; } // catch exceptions of type 'const std::exception&' catch (const std::exception& ex) { cerr << "error: " << ex.what() << endl; }
note:
there's standard exception deigned case of invalid parameters passed function. alternatively can do
double mysqrt(double dx) { // if user entered negative number, error condition if (dx < 0.0) { // throw exception of type invalid_sqrt_param throw std::invalid_argument("mysqrt: can not take sqrt of negative number"); } return sqrt(dx); }
Comments
Post a Comment