0

Basically I've got a function with a scope guard to do cleanup on exit.

And then a problem happens in the scope guard cleanup and it throws.

string f(void)
{
   scope_guard x(){ throw std::runtime_error("Failed to finalize stmt.");}

   return "ok";
}

So as I watch in my debugger, the return starts to happen, the scope guard goes out of scope and inside that, it throws.

msvc2017 gave me an unhandled exception exception or something like that.

I would think this should work unless there's something unpleasant about throwing in the middle of the stack unwind or something like that?

Any ideas?

stu
  • 8,461
  • 18
  • 74
  • 112
  • Obviously, your scope guard should be implemented not to throw? And in C++, you don't need to write code like this. –  May 08 '18 at 18:59
  • I guess this? https://stackoverflow.com/questions/130117/throwing-exceptions-out-of-a-destructor Says "It's fine unless there's already an exception being thrown, in which case your app terminates." – Hitobat May 08 '18 at 19:01
  • I don't write code like this, I inherit code like this. – stu May 08 '18 at 19:02
  • @Hitobat it's not exactly a destructor though. Maybe the same thinking applies but it isn't the same as throwing in a destructor. – stu May 08 '18 at 19:04
  • 3
    @stu well, the scope guard most probably implements its functionality through its destructor, unless it taps into compiler magic or something. – Quentin May 08 '18 at 19:06
  • 1
    Check that `scope_guard`'s destructor is `noexcept(false)` or equivalent. It's likely the destructor is `noexcept` which would prevent you from throwing as the end-of-scope action. – François Andrieux May 08 '18 at 19:11
  • @Quentin good point, it must, so it is in fact throwing from a destructor, but this is the first throw, the weird part is that it is after or during the return statement, and I'm not sure what's going on there. Or for that matter, if it's okay to return in a scope guard after the return has already happened... – stu May 09 '18 at 14:36

0 Answers0