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
}
精彩评论