Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ -The right way to throw and catch exceptions [duplicate]

Possible Duplicate:
throwing exceptions of objects on the stack, mem leak with new?

Do you throw exceptions in C++ with or without the new operator? Because both of these would throw an exception.

void KillUnicorns()
{
    throw IllegalActionException();
}

int main()
{
    try
    {
        KillUnicorns();
    }
    catch (IllegalActionException e)
    {
         // Handle exception
    }
    return 0;
}

Although the following example would leak memory?

void KillUnicorns()
{
    throw new IllegalActionException();
}

int main()
{
    try
    {
        KillUnicorns();
    }
    catch (IllegalActionException* e)
    {
         // Handle exception
    }
    return 0;
}

What's the right way to throw exceptions in C++?

like image 650
Kevin Avatar asked Apr 03 '11 15:04

Kevin


2 Answers

I would throw exception without using new:

void KillUnicorns()
{
    throw IllegalActionException();
}

And would catch it with const reference, as:

catch (const IllegalActionException & e)
{   // ^^^^ note const             ^^ note reference!

}

It avoids copy. It avoids new, and so saves you from using delete.

like image 88
Nawaz Avatar answered Oct 23 '22 09:10

Nawaz


Technically you can do both.

But it more traditional to throw objects:
Also note catch by const reference (this prevents slicing of the exception)

try
{
    KillUnicorns();
}
catch (IllegalActionException const& e)
{                         // ^^^^^^^^
     // Handle exception
}
like image 8
Martin York Avatar answered Oct 23 '22 10:10

Martin York