Re: What if new throws exeption?
In article <hgcqv8$atr$1@news.albasani.net>, Vladimir Jovic <vladaspams@gmail.com> wrote:
doublemaster007@gmail.com wrote:
Hi All
somePtr *obj =NULL; ----------------------------(1)
obj = new somePtr; -----------------------------(2)
if(obj!=NULL) ------------------------------(3)
{
//do somthing
}
Is this code correct?
Not really. If exception is thrown, you never get to your
test. So that test is useless.
That exception must be caught. Else your program is as flaky
as it gets.
Maybe. I can not compile it. See this:
http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.8
first, "new" doesnt return NULL. I have read this some where. Or is
that (1) ensures obj NULL after (2)
AFAIK, new throws exeption. So will the (3) be exexuted?
If (2) throws an exception, then (3) will not be executed.
Reason i am asking this is, Its become a practise that checking for
NULL instead of trying for exeption. Is the above code really correct?
That practice is for C, not for c++. In c++ you check for the exception.
You don't CHECK for exceptions. You CATCH them.
One more question. If new fails, Do we need to call the destructor of
obj explicitly?? AFAIK objected isnt contructed so we donot need to
call destructor..am i right???
No and yes.
1) No - for call the destructor. In 99.999% cases you do not need to
call destructor explicitly. Specially in this case
2) Yes - you are right
--
Programmer's Goldmine collections:
http://preciseinfo.org