On Apr 23, 4:13 pm, anon <a...@[EMAIL PROTECTED]
> wrote:
> Hello,
>
> for debugging purposes, I am using next base class for my exception
cl*****:
> const std::string errorMsg( __FILE__ + __LINE__ + "error message" );
> throw RandomError( errorMsg );
>
> I read on lots of places that the exception class should inherit from
> the std::exception class and should not use std::string, because it can
> throw. This article explains the
problem:http://www.boost.org/community/error_handling.html
>
> Can anyone recommend me a better way to implement the exception
> handling, which is going to give the runtime message when the error
> class is thrown?
>
> Thanks in advance.
The only reason std::string would throw is if your system ran out of
memory. If that is the trouble, then it is likely that the reason that
you are throwing in the first place is because the system ran out of
memory. In either case you get the same diagnostic.
The reason for the advise against using std::string is because not all
exceptions inherit from std::exception, and because of the existence
of throw specifications. However, every good programming guideline
will tell you not to use throw specifications, and to make sure that
your exception class inherits from std::exception, and that program
correctness should not rely on the type of exception thrown.
When you do this , all kinds of good thing happen. For instance
try{
throw RandomError("MYStuff");
}catch(std::exception const&e){
cout<<e.what();//either "out of memory" or "MYStuff"
}catch(...){
cout<<"Unknown"
}
program is still in a consistent state here no matter what exception
what thrown
the correct error message is just a nice to have (a VERY nice to have)
Given that either exception bad news, it really isnt worth the trouble
to go out of your way not to use a string, unless you were designing
something that didnt follow the guidelines above.
BTW this
const std::string errorMsg( __FILE__ + __LINE__ + "error message" );
does not do what you want. YOu reall want
std::ostringstream msg;msg<<__FILE__<<__LINE__<< "error message";
throw RandomError( msg.str() );
Lance
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|