Failure of new

G

Girish Pal Singh

Hi,
1. If the new operator fails what should be done to override it?
2. If we want to gurantee that function does not throws exception what
should be done?
 
R

Rolf Magnus

Girish said:
Hi,
1. If the new operator fails what should be done to override it?

Catch the exception that it throws. But if you're out of memory, most
programs can't do much more than just exit immediately, which the
exception already does if it's not caught.
2. If we want to gurantee that function does not throws exception what
should be done?

If it's a function you wrote yourself, declare it as something like:

void myfunction() throw();

If it's an already existing function, you can't. But you can catch all
the exceptions that it throws:

try
{
somefunction();
}
catch(...)
{
std::cout << "an exception was thrown" << std::endl;
}

If you're specifically talking about new, you can alternatively use
new(nothrow) from the header <new>. It will, instead of throwing an
exception, return a null pointer in the case of failure.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top