Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throw without arguments for failure signalling

Tags:

c++

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.

like image 891
Coder Avatar asked Feb 08 '11 10:02

Coder


People also ask

What happens when we throw an exception?

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.

What does throw () mean in C++?

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.

What happens when a throw statement is executed in C++?

In C++ throw; when executed inside a catch block rethrows the currently caught exception outside the block.

How do you throw an exception in CPP?

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.


2 Answers

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.

like image 54
sharptooth Avatar answered Oct 06 '22 00:10

sharptooth


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.

like image 21
Jan Hudec Avatar answered Oct 06 '22 00:10

Jan Hudec