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 no idea what happens if there is no initial exception to rethrow.
When an exception is thrown using the throw keyword, the flow of execution of the program is stopped and the control is transferred to the nearest enclosing try-catch block that matches the type of exception thrown. If no such match is found, the default exception handler terminates the program.
The throw keyword throws an exception when a problem is detected, which lets us create a custom error. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
In C++ throw; when executed inside a catch block rethrows the currently caught exception outside the block.
An exception in C++ is thrown by using the throw keyword from inside the try block. The throw keyword allows the programmer to define custom exceptions. Exception handlers in C++ are declared with the catch keyword, which is placed immediately after the try block.
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With