c++ catch error raised by PPL parallel_for - c++

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;)

Related

Why do programmers use both std::bad_alloc and std::exception. Is std::exception alone not sufficient

Consider the following code snippet
try {
goesWrong();
}
catch (const std::bad_alloc &e)
{
std::cout << "Catching bad_alloc: " << e.what() << std::endl;
}
catch (const std::exception &e)
{
std::cout << "Catching exception: " << e.what() << std::endl;
}
Why do we need to catch a lot of individual exceptions. Just std::exception at the end is enough to catch all exceptions isn't it ? Why an extra 4 lines of code to catch std::bad_alloc explicitly when std::exception is going to catch it anyway?
Why do we need to catch a lot of individual exceptions.
In general, because that allows different behaviour depending on the type of the caught exception.
In this case, there's need to do so, since this possibility is not taken advantage of.
Consider for example a case where you have allocated a large cache in memory. In that case, when catching std::bad_alloc, you might release the cache and try again, while that approach would not be useful in the case of other exceptions.
The separate catch statements are so that you have have different behaviour depending on the type of exception thrown.
For example you might be expecting a bad_alloc and can recover from it by trying again with a smaller allocation or by freeing memory elsewhere.
Just std::exception at the end is enough to catch all exceptions isn't it ?
No, catching std::exception is enough to catch all thrown exceptions which are derived from std::exception. In c++ std::exception doesn't have any special meaning, you can throw any type as an exception. It is recommended to derive from std::exception but not required.
There are even pitfalls like if you have multiple inheritance and your exception class derives from std::exception twice it won't be caught.
To catch all exceptions you need to catch ...:
struct my_exception {};
try
{
switch ( i )
{
case 1:
throw std::runtime_error( "i is 1" );
case 2:
// bad idea, who is responsible for freeing the exception? But perfectly legal
throw new std::runtime_error( "i is 1" );
case 3:
// you can throw numbers too
throw i;
case 4:
throw my_exception();
}
}
catch ( const std::exception& )
{
}
catch ( const my_exception& )
{
}
catch ( ... )
{
}
exception could be any expception while bad_alloc is more specific. Not only you might want to react differently for different kind of exceptions, but also it more clearly expresses what is going on. After all code is written to express your intention not just to make it work somehow.
More an addition to the answers given so far than a separate, own one:
Actually, you could base exception handling on evaluation of the what() string:
catch(std::exception const& e)
{
if(strcmp(e.what(), "some text"))
{
doThis();
}
else if(strstr(e.what(), "something"))
{
doThat();
}
// ...
}
However, this requires that you know the exact string contents. What, if these differ across different C++ implementations? What, if these are localised on some systems? Do you really want to cope with all such matters? Additionally, text processing is much more expensive than just catching different exceptions.
So with different exceptions, you gain portability, safety (consider typos in the strings you compare with...), easier and better readable code and, as a bonus, efficiency.

Catch(...) with unknown object - how do I identify what was thrown?

I have a library I use that throws something, but I don't know how to identify what was being thrown.
Sample code to reproduce this:
int main()
{
char* memoryOutOfBounds;
unsigned __int64 bigNumber = -1;
try {
throw std::string("Test");
memoryOutOfBounds = new char[bigNumber];
}
catch (const std::bad_alloc& ex)
{
printf("Exception: %s\n", ex.what());
}
catch (...)
{
printf("Unknown.\n");
}
return 0;
}
The new char[bigNumber] will throw a std::bad_alloc, which is derived from std::exception and will enter the first branch. The other one, throw std::string will enter the second branch. How can I check the object that was thrown? I tried with a catch(void*) in the hopes to catch any object in memory, but that did not happen, so how can I find out what was thrown and from there debug what may have caused this?
catch (...) {}
means: Catch absolute everything that was thrown and drop it. This is only meant as a safeguard, so no exceptions fly out of the window and bring down the whole house. (Aka: Application Termination by Unhandled Exception")
There is no way to tell what was thrown in here.
But as you actually know that an std::string can be thrown, you can catch it in a
catch (const std::string& s) {}
block. You do need to know what (type) was thrown whenever you want to catch exceptions.
However, most libraries which add their own types for exceptions will have them inherit from std::exception. Therefore a
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
block should get them.
If they do not inherit from std::exception and/or block the what() method, it is a stupid way to make the usage of their library extra difficult.
However, somewhere in the documentation of the library the exception throwing behaviour should be explained.
Edit : I think that Point 1. under "How should I design my exception classes" on the Boost Error Handling document is something every library developer should keep in mind. And hopefully the developers of your library did keep that principle in mind. ;-)
There really is no standard C++ way to query any information about the exception that is being thrown. Which is unfortunate, because the runtime has that information in order to match catch blocks. But there is just no access to that information in user code.
If it's purely for research purposes, like just finding out what the type is because the library you're using lacks documentation, you could use std::current_exception() to get a std::exception_ptr object that stores (or references) the thrown exception internally. This type is implementation-defined, but your debugger might happen to provide you with enough information.
#include <exception>
void foo()
{
try
{
function_that_throws();
}
catch(...)
{
std::exception_ptr p = std::current_exception();
// break here and inspect 'p' with a debugger
}
}
This stackoverflow post would be helpful-
C++ get description of an exception caught in catch(...) block
Since C++11 you can capture the current exception with a pointer:
std::exception_ptr p; // default initialization is to nullptr
try {
throw std::string("Test");
}
catch(...)
{
p = std::current_exception();
}

Is it important that what() does not throw (exception classes)?

An exercise from C++ Primer asks
Why is it important that the what function [of exception classes] doesn’t throw?
Since there is no way to check my answer I was hoping to get an opinion. I thought possibly that it is an error (maybe terminate would've been called) to throw another exception during a catch clause (other than a rethrow throw;) while the current exception object is still being handled. It seems that is not the case though and it is completely okay to throw out of catch clauses:
#include <iostream>
using namespace std;
int main(){
try{
try{
throw exception();
} catch(exception err){ throw exception();}
} catch(exception err){ cout << "caught"} //compiles and runs fine, outputs "caught"
}
So program terminations are not a worry. It seems then, any problem that arises from what() throwing should, at the very least, be rectifiable by the user if they were so inclined.
Maybe then, the importance might be that while handling an error we do not want further unexpected errors to occur? Throws inside catch clauses are mainly intended for sending the exception object further up the call chain. A user may receive an error from deep in his program and does not want to worry that the error caught has to be associated with its own try block. Or maybe what() having its own throw may also lead to recursive effects (e.g. what() throws an exception, then we catch this exception and call what() but this then throws, and so on) meaning it might become impossible to handle any errors? How drastic can it be for what() to potentially throw?
I think there's nothing unclear - it's just as you described. If .what() method of an exception class throws an error, the whole catch effort was wasted:
try {
someDangerousOperation();
}
catch(std::exception e) {
// Ooops, instead of false,
//we get another exception totally unrelated to original error
someLogClassOrWhatever.save(e.what());
return false;
}
return true;
And Imagine the crazy code if you were expected to deal with what()'s exceptions:
try {
someDangerousOperation();
}
catch(std::exception e) {
// Not very fun
try {
someLogClassOrWhatever.save(e.what());
}
catch(...) {
alsoWhatHasFailedThatIsReallyGreat();
}
return false;
}
I think there's nothing more in that, probably the question is so simple it seems there must be some catch hiding in it. I think it's not the case.
std::exception::what() is noexcept. Consequently, if it throws, std::terminate is called. Yes, this is important.
Image a very curious coder with a slight tendency towards being a control freak (I know a couple of them myself), he really wants to know what is going wrong in his program and logs all errors with ex.what(). So he codes
try {
code();
}
catch(std::exception &e) {
std::cout<<e.what()
}
He is pretty pleased with the world in general and with himself in particular. But now it crosses his mind, that e.what() could throw an exception as well. So he is codes:
try{
try {
code();
}
catch(std::exception &e) {
std::cout<<e.what()
}
}
catch(std::exception &e) {
std::cout<<e.what()
}
A minute later he notices, that there is again an uncaught exception possible! Remember, he is a control freak, so he is going to write another try-catch block and than another and another
So you can bet any money, his project will be late - how could you do something like this to my friend? So please make sure e.what() doesn't throw:)
I guess it is the reason behind what being noexcept.

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)

Throwing an exception while handling an exception

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.
}