throw new std::exception vs throw std::exception

Solution 1:

The conventional way to throw and catch exceptions is to throw an exception object and to catch it by reference (usually const reference). The C++ language requires the compiler to generate the appropriate code to construct the exception object and to properly clean it up at the appropriate time.

Throwing a pointer to a dynamically allocated object is never a good idea. Exceptions are supposed to enable you to write more robust code in the face of error conditions. If you throw an exception object in the conventional manner you can be sure that whether it is caught by a catch clause naming the correct type, by a catch (...), whether it is then re-thrown or not it will be destroyed correctly at the appropriate time. (The only exception being if it is never caught at all but this is a non-recoverable situation whichever way you look at it.)

If you throw a pointer to a dynamically allocated object you have to be sure that whatever the call stack looks like at the point you want to throw your exception there is a catch block that names the correct pointer type and has the appropriate delete call. Your exception must never be caught by catch (...) unless that block re-throws the exception which is then caught by another catch block that does deal correctly with the exception.

Effectively, this means you've taken the exception handling feature that should make it easier to write robust code and made it very hard to write code that is correct in all situations. This is leaving aside the issue that it will be almost impossible to act as library code for client code that won't be expecting this feature.

Solution 2:

No need to use new when throwing exception.

Just write:

throw yourexception(yourmessage);

and catch as :

catch(yourexception const & e)
{
      //your code (probably logging related code)
}

Note that yourexception should derive from std::exception directly or indirectly.

Solution 3:

Throwing new std::exception is correct if the call site is expecting to catch a std::exception*. But nobody will be expecting to catch a pointer to an exception. Even if you document that's what your function does and people read the documentation, they're still liable to forget and try to catch a reference to a std::exception object instead.

Solution 4:

The C++ FAQ has a nice discussion on this:

  1. https://isocpp.org/wiki/faq/exceptions#what-to-catch
  2. https://isocpp.org/wiki/faq/exceptions#catch-by-ptr-in-mfc

Basically "unless there's a good reason not to, catch by reference. Avoid catching by value, since that causes a copy to be made and the copy can have different behavior from what was thrown. Only under very special circumstances should you catch by pointer."