开发者

throw without arguments for failure signalling

开发者 https://www.devze.com 2023-02-09 09:29 出处:网络
Is it ok to just call throw; from constructor if something goes awry, and you have no idea how to recover?

Is it ok to just call throw; from constructor if something goes awry, and you have no idea how to recover?

The idea is to let the app crash with a dump, as the state is unknown. Or should you always specify an argument?

From MSDN I only found that it rethrows if there is no argument, but开发者_StackOverflow no idea what happens if there is no initial exception to rethrow.


No. throw; is a special syntax that re-throws current exception. It only makes sense inside catch blocks (or code called from one) to continue propagating the exception.

Just use:

#include <stdexcept>
...
throw std::runtime_error("some description");

or even just

throw "some description";

but the later is uglier to handle and just generally frowned upon.


If there's no exception currently being processed throw; will lead to terminate() being called immediately and that will end your program abnormally. That is not very convenient - you'll have less information about what happened compared to throwing a meaningful exception. You could have thrown a meaningful exception, catch it at the top level (like main()), write some diagnostics and then end the program.


An ASSERT might make your life easier to dignose what's going wrong


While technically you can call it, it won't do what you'd like.

The simplest solution is to call throw std::runtime_exception("thrown from Foo");, which at the same time gives some feedback about what was going on.


When you say "no idea how to recover" what you mean I presume is that at this point you do not know how to handle the error?

Perhaps you are not getting the point of exceptions. You throw information: that the exception occurred and why. The call-stack is then unwound to the point where it can be handled. At that point in the code we know how, if possible, to recover.


Technically, you can do that because throw without argument and without an active exception just calls terminate() which by default calls abort(). I prefer calling abort() directly, it requires less cognitive effort to recognize what is going on.

0

精彩评论

暂无评论...
验证码 换一张
取 消