Re: Usage of throw
On Oct 3, 3:56 pm, Olivier Delannoy <Olivier.Delan...@gmail.com>
wrote:
Hi all,
I am interesting in adding contextual information (such as file/line)
in debug mode and not in production mode. In order to do that I plan
on adding a macro of the form :
MY_THROW(exp) which is going to be translated into :
- in release mode: throw (exp)
- in debug mode: throw (exp).context(__FILE__, __LINE__)
In order to do that I need to make sure all my exception provide a
context method of the form :
class MyExp
{
...
public:
MyExp& context(char* file, int line) { ... ; return *this;}
};
Now in a test program I do:
void f()
{
MY_THROW(MyExp()); // In Debug mode: throw
(MyExp()).context(__FILE__, __LINE__);
}
int main()
{
try
{
f();}
catch(MyExp& e)
{
// Do something with e
}
}
This program works nice but I don't feel confortable with this kind of
use of throw. Is it safe/portable accross compiler/ in respect of
standards to throw an exception as I do ?
Is there any better way to do this ?
I use a macro similar to the following (pretending the '\'s are
there)--
#define CONTEXTTHROW(Ex,Msg)
do{
std::ostringstream tmp;
tmp<<__FILE__<<":"<<__LINE__<<": "<<Msg;
throw Ex(tmp.str());
}while(0)
Then all I do is
int ret=do_something(arg);
if(ret)CONTEXTTHROW(std::runtime_error,"do_something("<<arg<<") failed
with ret ="<<ret);
And of course when the program runs, I get lots of info about where
the failure was, and the context of the failure. Yes there is much
formatting overhead, but I in the industry I'm in finding and fixing
bugs quickly is extremely important. I am not so concerned on just how
fast error objects can be created and thrown, just that once they are
I want to resolve the matter quickly -- besides the overhead of
formatting errors NEVER appears on my profiler.
I have written apps where some exception messages are intended for
external clients (i.e. wrong input), and in those cases of course
there are more msg formatting options.
In real life the macro may be cluttered with _DEBUG macros and such,
and plus I use my own lightweight version of ostringstream -- I also
have version that format errno and such when wrapping POSIX functions,
and other nifty things.
Lance
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]