2

I know that we can specify the compiler that a function is not throwing an exception by using noexcept specifier but noxecept functions can still throw exceptions . So, how to prevent destructor from throwing an exception ?

  • 4
    All I can say is code it properly. Do you have examples of code in which you believe the destructor could possibly throw an exception? – Mike Feb 27 '15 at 4:04
  • 1
    Do not use the throw keyword in your destructor, and catch exceptions that called functions throw? Not sure how to "guarantee" this, there are very few guarantees in programming. – user22815 Feb 27 '15 at 4:14
  • I asked this question because I came across an exercise in c++ primer , which says that - "If you think one of your destructors might throw, change the code so that it cannot throw. " – Ayush Chaurasia Feb 27 '15 at 4:25
  • How would a function marked noexcept still throw an exception? If a function marked noexcept throws an exception, the standard requires std::terminate to be called. std::terminate's requirement is: "A terminate_handler shall terminate execution of the program without returning to the caller." – Jerry Coffin Feb 28 '15 at 0:18
4

If a function is declared as nothrow throws an exception anyway, that is a bug pure and simple.

Given that, to ensure your destructors don't throw any exceptions, there are two paths:

  1. Only call functions that are known not to throw an exception (either because they are declared with nothrow, they are documented not to throw, or they are implemented in a language without exceptions)
  2. Wrap the calls in your destructor that could throw in a try { } catch(...) block.
| improve this answer | |
2

Just mark it noexcept.
In C++11 and following, your destructor is automatically declared noexcept unless at least one (base- or member-) subobject's destructor can throw, or you explicitly give a different exception-specification.

And if your function is marked non-throwing, it won't throw, ever, whatever you try.

Instead, it will:

  1. If your exception-specification is dynamic (throw()), call std::unexpected().
  2. If your exception-specification is not dynamic, or std::unexpected() throws, call std::terminate() to abort the program.
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.