Re: why exceptions?
On Sep 23, 12:15 pm, ramu <ramu....@gmail.com> wrote:
Hi,
Why exceptions ?
Suppose we are writing a code like this
class test { };
int main()
{
test *ob = new test;
if (ob == NULL)
cout<<"Memory is not allocated"<<endl;
//....
As others have pointed out, this
test *ob = new test;
is really a two step process. Just testing for NULL doesn't tell
you if the memory allocation failed or the constructor for test
failed.
try {
test *obj = new test;
}
catch( std::bad_alloc const & ba )
{
.... // do something in low memory condition
}
catch( std::runtime_error const &re )
{
... // do something because ctor failed
}
This may be an improvement, but I'll wager 80% or more (insert your
favorite number here) of programmers have no idea of how to handle
a low memory error. I'll include myself in that 80%. What happens
if the object is relatively small? Say 10's or 100's of bytes.
Chances are any subsequent recovery functions will require memory
and will fail also. If the object was
very large, you might stand a chance of reporting the error
and doing a graceful shutdown, if that is even an option. All
the programs I write are for the PC desktop and no human
life is at stake. I don't think I've had to handle an out of memory
error since probably 2000. I do have to handle errors when
resources aren't available though. As shown above, my job is made
easier with the use of exceptions.
Typically I surround a major functional block with the try/catch
and don't try to handle recovery on a low level basis. For example
void HandleUserMenuSelectionToDoSomething()
{
try {
DoSomethingVeryImportant();
}
catch( FileTypeErrors const &fe ) {}
catch( ResourceTypeErrors const &re ) {}
catch( ... ) {}