C ++ is the right way to throw and catch exceptions

Possible duplicate:
throwing object exceptions on the stack, memory leak with new?

Are you making exceptions in C ++ with or without the new operator? Because both of them cause an exception.

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

Although the following example will be a memory leak?

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

What is the correct way to throw exceptions in C ++?

+8
c ++ memory-leaks exception exception-handling
source share
2 answers

I would throw an exception without using new :

 void KillUnicorns() { throw IllegalActionException(); } 

And there will be a catch using a const reference, like:

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

This avoids copying. It avoids new and therefore saves you from using delete .

+9
source share

Technically, you can do both.

But it's more traditional to throw objects:
Also pay attention to catch by const reference (this prevents throwing exceptions)

 try { KillUnicorns(); } catch (IllegalActionException const& e) { // ^^^^^^^^ // Handle exception } 
+8
source share

All Articles