开发者

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

开发者 https://www.devze.com 2023-02-21 14:07 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: throwing exceptions of objects on the stack, mem leak with new?
This question already has answers here: Closed 11 years ago.

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;
}

开发者_StackOverflow中文版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++?


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.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消