Re: exception and polymorphism problem
BobR <removeBadBobR@worldnet.att.net> wrote in message ...
josh <xdevel1999@gmail.com> wrote in message ...
I do it but still the code doesn't work.
...
try{ throw Exception(); }
catch(exception &e){ cout << e.what() << endl; }
...
here e is a reference to the new Exception() created so
at run-time e.what() should point to my Exception class
and to print "exception!" but it doesn't do that and print
9Exception ... why?
Hi Bob.... Oh wait, I'm Bob! <G> [answering my own post]
Hi josh,
Ok, after a very little testing, it seems that your class (derived from
std::exception) 'slices', removing your '*.what() when passed to the
'catch(std::exception&)'. By the time I downcasted it to 'Exception' there
is a problem with 'const' which I couldn't find a combination to (for the
few minutes I tried).
[ time for an expert to 'splain it. <G> ]
Catch the right thing!
// > catch( Exception const &e ){
catch( Exception &e ){ // 'const' no work.
cout << e.what() << endl;
}
.... or, re-throw() the std::exception() in your derived class.
I am guessing (have not tested this yet), so, try it, see what happens.
If you derive your class from 'std::runtime_error', the 'slicing' does not
happen.
( no '*.what()' in 'Exception3' to slice, duh! )
class Exception3 : public std::runtime_error { public:
Exception3( std::string const &msg = "exception3!")
: std::runtime_error( msg ){}
};
{ // main or function
try{
throw Exception3();
}
catch( std::exception const &e ){
cout<<"caught std::exception= " << e.what() << std::endl;
} // catch( exception& )
try{
throw Exception();
}
catch( std::exception const &e ){
cout<<"caught std::exception= " << e.what() << std::endl;
} // catch( exception& )
}
// output: caught std::exception= exception3!
// output: caught std::exception= 9Exception // sliced
Is there a reason you cannot use 'Exception3'?
( remember, if you just want to catch *any* exception, you can set up
default handlers.)
--
Bob R
POVrookie