I have my own exception in my application. And the moment I throw it like this:
throw new CChristianLifeMinistryEntryException(strError);
Understandably code analysis triggers this because I have used new
.
It is suggesting that I use make_unique
and I am trying to establish if that is the correct way to update this code.
CodePudding user response:
In C exceptions are normally derived from std::exception
and are thrown by value, and caught by reference. This way you don't need to manage lifetime (don't need to delete some exceptions after handling and not delete others).
Like throw std::runtime_error(str_error);
.
MFC's approach of throwing reference with new
predates C compiler exception support, so there was a way to throw a pointer exception, but not arbitrary type of exception. It is not recommended for the new code.
There's special smart pointer for exceptions called exception_ptr
, it is usually needed to transfer exceptions between threads, not to wrap exceptions being thrown.
If you wrap an exception with unique_ptr
, you'll have to catch it wrapped, and this catch
will not catch derived exception, because different unique_ptr
and not derived from each other, so wrapping exceptions this way is definitely not a good idea.