You could check for the bad_alloc exception thrown by new, and then in the catch block throw your own exception as you want to.
Or you could allocate like so: firstPtr = new (std::nothrow) fstream();. Then new doesn't throw if there is an error, it returns a NULL pointer, which you can then check for :)
Well ,that's sounds nice . But if I check "if (firstPtr == NULL)" I get that the pointer is indeed
points to NULL , that's why that check ain't helpful.
How do I use the bad_alloc ?
thank you
Dave
EDIT :
One more thing :
1 2 3
this one : firstPtr = new (std::nothrow) fstream();
and that one : firstPtr = new fstream();
No, not the same. They both allocate memory on the heap for an fstream. However, the first one returns a null pointer in the event of an error. The second throws an exception of type std::bad_alloc.
To do the bad_alloc thing, you catch an exception just as you do in your program:
Oh, and I noticed two typos in your second code segment (in your original post). On line 1 you wrote Class not class and on line 19 you missed an opening bracket after if.
try
{
firstPtr = new fstream();
if (firstPtr == NULL)
throw DbAllocationException(ALLOCATION_ERROR);
}
catch (runtime_error& err)
{
cout << err.what() << endl;
}
try
{
secondPtr = new fstream();
if (secondPtr == NULL)
throw DbAllocationException(ALLOCATION_ERROR);
}
catch (runtime_error& err)
{
cout << err.what() << endl;
}
// remark : ALLOCATION_ERROR is a const string within my code
this code compiled just fine , there were no catches and no errors .
My question is , do you think this is enough , or should I use the option above that you offered ?
Again,thanks