Throwing an exception while handling an exception - c++

I'm reading the "C++ Programming Language 4th edition" book and have a question regarding a paragraph about exception handling:
There are cases where exception handling must be abandoned for less
subtle error-handling techniques. The guiding principles are:
Don't throw an exception while handling an exception.
Don't throw an exception that can't be caught.
If the exception-handling implementation catches you doing either, it
will terminate your program.
Could someone give me an example of the first situtation? Only something like this comes to my mind but it's a valid code according to g++:
try
{
throw 1;
}
catch(...)
{
try
{
throw 2;
}
catch(...)
{
cout << "OK";
}
}

That's a bit misleading; it's fine to throw from an exception handler (which is what I'd understand by "while handling an exception"), as long as there's another handler to catch it.
The problem is if you throw an exception from the destructor of an object that's being destroyed during stack unwinding. In that case, there are two unhandled exceptions, and the usual exception mechanism can only deal with one; so the response is to call terminate.
Example:
struct dodgy {~dodgy() {throw "Don't do this!";}};
try {
dodgy d;
throw 1;
} catch (...) {
// Never reached: destroying `d` killed the program.
}

Related

Why rethrow an exception

In C++, why would you want to rethrow an exception. Why not let the current catch block handle the exception. For what reasons would you rethrow an exception to another try/catch block?
An exception is thrown when a function cannot meet its contract (what it promises the caller it will do). When a function calls another function that throws an exception, there are four main approaches to how it might respond:
Catch the exception and handle it. This should only be done if the function is able to meet its contract despite the exception being thrown. If it catches the exception but fails to meet its contract, it is hiding a problem from the calling code.
Allow the exception to propagate. This should be done if the exception cannot be handled by this function (that is, the function is unable to meet its contract because the exception has been thrown), and if the exception exposes the appropriate information to the calling code.
Catch the exception, do some clean-up and/or add extra info, and rethrow it. This should be done if the exception cannot be handled by this function, but it needs to do some cleaning up before propagating it. It can also provide extra information to help with handling/debugging the exception (I often think of the programmer as the very last exception handler).
Catch the exception and throw a different exception (perhaps wrapping the original). This should be done if the exception cannot be handled by this function, but a different exception better expresses the problem to the calling code.
Why not let the current catch block handle the exception. For what reasons would you rethrow an exception to another try/catch block?
The idea behind exceptions is that you throw them at the error site and handle them down the stack, where you have enough information to handle the error.
Conversely, there are cases when you must do something in case of an error, but still don't know how to handle the error (this is the case when you rethrow).
Example:
void connect_and_notify(int connection_data)
{
try
{
create_network_connection(connection_data); // defined somewhere else
notify("connection open"); // same (notify event listeners)
}
catch(const std::runtime_error&)
{
notify("connection failed");
throw;
}
}
Client code:
void terminal_app_controller()
{
try
{
connect_and_notify(1);
}
catch(const std::runtime_error& err)
{
std::cerr << "Connection failed;\n";
exit(1); // this is usually bad bad code but whatever
}
}
void ongoing_server_controller()
{
bool connected = false;
int connection = 1;
while(!connected)
{
try
{
connect_and_notify(1);
connected = true;
}
catch(const std::runtime_error&)
{
connection++;
}
}
}
In the two usage scenarios, the error is handled differently (connect_and_notify has no way of knowing that, but still, on a failed connection it must notify listeners).
Each function has a different policy to handle the exception and this means different catch blocks.
I very much dislike anything like
catch (std::exception&) {
... // do some cleanup
throw;
}
RAII is the correct solution to that problem. Even:
catch (std::exception&) {
... // do some logging here
throw;
}
can be handled with RAII, although it is less intuitive.
BUT - where I have rethrown is any situation where 3rd-part (or vendor-supplied) code throws "generic" exceptions with state. For example, when logging telematics messages to a database, I know that I often receive duplicate copies of the same message. Each message has a unique ID - so a primary key violation in my DB is an "innocent" error that should be silently ignored.
Unfortunately, the DB framework we use doesn't throw a specific exception for PK violations - so we need to catch the generic dbexception and check what its reason code is to decide what to do. Hence:
catch (db::exception& e) {
if (e.reason != db::exception::reason::pk_violation)
throw;
}
Also, piwi mentioned internal state. An example would be
for (;;) {
try {
...
}
catch (some_exception& e) {
if (retry_count > 3)
throw;
}
}
Remember: If you are going to rethrow, always catch by reference to avoid slicing the exception object. (You should usually catch by ref anyway, but it is even more important when rethrowing)

c++ exception handling

Learning "try & catch". What is wrong with the following code?
Thanks for the advice.
Error in execution:
terminate called without an active exception
Aborted
The code:
#include <stdio.h>
int main()
{
int a = 3;
try
{
if (a < 5)
throw;
}
catch (...)
{
printf ("captured\n");
}
return 0;
}
Your throw; statement tries to rethrow a current exception but there probably isn't one. You need something like
throw some_exception_object();
Inside of a try block, you have to specify what to throw. The only place you can use throw by itself is inside of a catch block to re-throw the current exception. If you call throw by itself without a current exception being active, you will kill your app, as you have already discovered.
Try this:
#include <stdio.h>
int main()
{
int a = 3;
try
{
if (a < 5)
throw 1; // throws an int
}
catch (...)
{
printf ("captured\n");
}
return 0;
}
You can throw anything you want, as long as you throw something.
There are four things, two major and two minor. One thing at a time...
1. Rethrow usage w/o active exception
A throw; statement is used to re-throw an exception that is currently caught. For example:
try {
do_something();
} catch (const std::exception &) {
throw; // This statement re-throws an exception that was caught in this "catch" block.
}
In your case, you are using throw; without catching any exceptions (in order words — it does not appear inside catch block directly or indirectly), thus your program is terminated. When there is a need to throw and not to re-throw an exception, like in your case, you must specify an exception object to be thrown. For example:
throw std::runtime_error("Something bad happened");
2. catch-all clause which does not re-throw a caught exception
Your catch-all clause (catch (...)) is perfectly legal C++. However, it does not re-throw caught exception. Even though it is a legal C++ code, such a usage is a taboo. C and C++ runtime is usually using special types of exceptions to implement certain functionality. For example, NPTL is using exceptions to implement a thread cancellation. If you catch that exception using catch (...), a thread won't be cancelled and you are going to have a bad time. Generally, you have to catch exceptions by their types. In almost all cases, exceptions are inherited from std::exception, and so you have to write catch (const std::exception &) or, if you expect to catch an exact type, - catch(const TypeYouExpect &). If you must, however, use catch-all, remember to re-throw. For example:
try {
do_something();
} catch (...) {
throw; // DO NOT FORGET TO RE-THROW.
}
3. Header naming...
You are including C header whereas C++ provides its own headers for standard C features. So, header:
#include <stdio.h>
.. should be:
#include <cstdio>
C++ specific C functions get special treatment. For example, they become available in std namespace. So that you can use std::open() instead of just open() or ::open(). No big deal, but is highly recommended way to go.
4. Return from main.
Unlike C, C++'s main() function is very special. It allows you not to have return 0;. This is a default behavior. So, unless you really need to return some value, you may save yourself some time by not typing return 0;. Remember, however, that main is the only function like that, and that everywhere else you must explicitly return something unless a function is marked void.
Hope it helps. Good Luck!
You need to actually throw some object. Even something as simple as
throw "error";
will catch the error like you want it to.
see it in action here
The statement to throw an exception is:
throw <expression>;
This statement:
throw;
is also called the re-throw statement and is use to re-throw an existing exception that has been caught. It is typically used in a catch block, for example, you look at the exception and decide if you can continue, retry or abort. In case you decide to abort, you re-throw the exception so that somebody else down the call stack will catch it and handle this error.
For example:
// getResult() calls can fail with a deadlock exception
// This method will retry up to 3 times before failing
Result getResultWithRetry()
{
int nbTry = 3;
for(;;) {
try {
return getResult();
} catch (DeadLockException& e) {
if (nbTry == 0) {
throw; // re-throw the deadlock exception
}
}
--nbTry;
}
}

c++ catch error raised by PPL parallel_for

I have written this piece of code to catch error launched by ppl
try
{
parallel_for (m_row_start, m_row_end + 1, [&functionEvaluation,varModel_,this](int i)
{
// do things
});
}
catch(const std::exception error_)
{
QString t(error_.what());
}
try
{
return functionEvaluation.combine(plus<double>());
}
catch(const std::exception error_)
{
QString t(error_.what());
}
No error is caught although I have strong suspicion that it does have exception raised (a larger try{}catch(...){} it catching an std::exception, with no clear message.
I am right with my syntax for catching exception raised in ppl code?
Your syntax is correct although there's no reason you couldn't catch by reference to avoid unnecessary copying of the exception object:
catch(const std::exception & error_)
Check that the exception thrown actually derives from std::exception.
The PPL will only allow exceptions to propagate once all the threads have completed, could you have a thread which is still running preventing you from seeing the exception?
For debugging purposes, you could add an extra catch block:
catch(...)
{
cout << "Unknown exception" << endl;
}
Just to check if you are getting any kind of exception thrown, however I wouldn't leave this in production code because there's no way to usefully do anything with the exception.
First, check what is thrown. If you mistype the catch, it will not react. Maybe it simply is the CONST marker? const-type is not the same as non-const-type, but I actually don't remember well if catches are const-volatile-sensitive.
Second, unless strong reasons arise, always catch by reference:
catch(std::exception& error)
If you do not, then an exception copying will occur: http://www.parashift.com/c++-faq/what-to-catch.html By copying I mean object-copying, not re-raising;)

Nested try-catch blocks?

int main ()
{
try
{
try
{
throw 5;
}
catch (int n)
{
throw;
}
}
catch (...)
{
cout << "Exception occurred";
}
}
This prints out "Exception occured" but
int main ()
{
try
{
try
{
throw;
}
catch (...)
{
throw;
}
}
catch (...)
{
cout << "Exception occurred";
}
}
This just errors. It seems like I'm doing the try-catch's exactly the same! The only difference is that in the first case I'm throwing an int, then a general exception, but in the second case, I'm throwing a general exception both times. Is the program confused as to which catch to go to?
There's no such thing as "general exception" and you throw no such thing.
In the first example, you throw an int, then you re-throw the exception that you are handling. That's the meaning of throw without an argument.
In the second example you start with an attempt to re-throw an exception that you are handling. As you are not handling an exception at that time, you get an error.
Your 2nd example terminates the program with a good error message (at least using g++ 4.6.1):
terminate called without an active exception
Aborted
This happens because you are trying to re-throw an exception, but since there are no active exception, the program terminates.
The current c++11 draft, in chapter 15.5.1 says this:
In some situations exception handling must be abandoned for less
subtle error handling techniques.
Then in the list of cases when std::terminate is called is this:
when a throw-expression with no operand attempts to rethrow an
exception and no exception is being handled (15.1),
So, the behavior from your 2nd example is well defined in the standard.

What does a single "throw;" statement do?

These days, I have been reading a lot the C++ F.A.Q and especially this page.
Reading through the section I discovered a "technique" that the author calls "exception dispatcher" that allows someone to group all his exception handling in one handy function:
void handleException()
{
try {
throw; // ?!
}
catch (MyException& e) {
//...code to handle MyException...
}
catch (YourException& e) {
//...code to handle YourException...
}
}
void f()
{
try {
//...something that might throw...
}
catch (...) {
handleException();
}
}
What bothers me is the single throw; statement: if you consider the given example then sure, it is obvious what it does: it rethrows the exception first caught in f() and deals with it again.
But what if I call handleException() on its own, directly, without doing it from a catch() clause ? Is there any specified behavior ?
Additionally for bonus points, is there any other "weird" (probably not the good word) use of throw that you know of ?
Thank you.
If you do a throw; on its own, and there isn't a current exception for it to rethrow, then the program ends abruptly. (More specifically, terminate() is called.)
Note that throw; is the only safe way to re-throw the current exception - it's not equivalent to
catch (exception const & e) { throw e; }
Yes, it specified behavior, it will call terminate;
15.1, para 8: If no exception is presently being handled, executing a
throw expression with no operand calls
terminate() (15.5.1).
That's so-called exception handler. It rethrows the "current exception" if any. If there's no exception currently being handled terminate() will be called.