How to catch exceptions from multiple tasks in Casablanca - c++

I'm trying to join two pplx tasks using the && operator of task, where both sub tasks can throw exceptions.
I understand from the ppl documentation that I can catch an exception in a final, task-based continuation. This works in Casablanca as well.
However, I can catch only one exception in my final continuation. If both sub tasks throw, one remains unhandled.
Here's a minimal example illustrating my problem:
#include <pplx/pplxtasks.h>
#include <iostream>
int main(int argc, char *argv[])
{
int a = 0; int b = 0;
auto t1 = pplx::create_task([a] { return a+1; })
.then([](int a) { throw std::runtime_error("a");
return a+1; });
auto t2 = pplx::create_task([b] { return b+1; })
.then([](int b) { throw std::runtime_error("b");
return b+1; });
(t1 && t2)
.then([] (std::vector<int>) { /*...*/ })
.then([] (pplx::task<void> prev) {
try {
prev.get();
} catch (std::runtime_error e) {
std::cout << "caught " << e.what() << std::endl;
}
});
std::cin.get();
}
The try/catch is able to catch whichever of the two exceptions occurs first. How can I catch the other?

You would have to add a final task-based continuation to each sub-task.
I would suggest re-throwing any exception you catch, however, that would likely be a bad idea since the continuation task doesn't realize that the 2 exceptions are equivalent see below example for proof.
Output:
caught a
caught final a
caught b
Also, if you remove the sleep, you will receive a "Trace/breakpoint trap" exception.
#include <pplx/pplxtasks.h>
#include <iostream>
int main(int argc, char *argv[])
{
int a = 0; int b = 2;
auto t1 = pplx::create_task([a] { return a+1; })
.then([](int a) { throw std::runtime_error("a"); return a+1; })
.then([] (pplx::task<int> prev)
{
int retVal = -1;
try
{
retVal = prev.get();
}
catch (std::runtime_error e)
{
std::cout << "caught " << e.what() << std::endl;
throw e;
}
return retVal;
});
auto t2 = pplx::create_task([b] { return b+1; })
.then([](int b) { throw std::runtime_error("b"); return b+1; })
.then([] (pplx::task<int> prev)
{
int retVal = -1;
try
{
sleep(1);
retVal = prev.get();
}
catch (std::runtime_error e)
{
std::cout << "caught " << e.what() << std::endl;
throw e;
}
return retVal;
});
(t1 && t2)
.then([] (std::vector<int> v) { for(int i : v) { std::cout << i << std::endl; } })
.then([] (pplx::task<void> prev)
{
try
{
prev.get();
}
catch (std::runtime_error e)
{
std::cout << "caught final " << e.what() << std::endl;
}
}).get();
}

Related

C++ - Exception in Constructor

I have a problem. I must throw an exception in the constructor One() but do not know how do I suppose to catch it. Can someone suggest something? I have tried this method: Throwing exceptions from constructors , What happens if a constructor throws an exception?
My code:
class One
{
int a, b;
public:
One()
{
a = 7;
b = 0;
if (b == 0)
{
throw "except";
}
}
};
int main()
{
One j;
try
{
cout << "good";
}
catch(const char *str)
{
cout << str;
}
}
Place the variable definition inside the try block:
try
{
One j;
std::cout << "good";
}
catch(const char *str)
{
std::cout << str;
}
First of all, don't throw non exception. 2. If you call constructor inside the try block, you can catch it then.
#include <iostream>
#include <stdexcept>
class One
{
int a, b;
public:
One():
a(7),
b(0)
{
if (b == 0) {
throw std::runtime_error("except");
}
}
};
...
try {
One j;
std::cout << "good" << std::endl;
} catch(std::exception& e) {
std::cerr << e.what() << std::endl;
}
Another solution if you don't want to have the whole code inside a try..catch block:
int main()
{
One* j = nullptr;
try
{
j = new One;
cout << "good";
} catch (const char *str)
{
cout << str;
return 0;
}
// continue with object in j ...
}
And of course you should a smart pointer in this case:
int main()
{
std::unique_ptr< One> j;
try
{
j.reset( new One()); // or use std::make_unique<>()
cout << "good";
} catch (const char *str)
{
cout << str;
return 0;
}
// continue with object in j ...
}

Catching overflows with boost::lexical_cast

I want to catch boost::lexicat_cast overflows the same way I can catch boost::numeric_cast overflows. Is it possible?
The first try block below throws a boost::numeric::negative_overflow.
The second block does not throw an exception (isn't this a lexical_cast bug?)
Though unsigned int is used in the example below, I am looking for a method that would work for any integer type.
#include <boost/numeric/conversion/cast.hpp>
#include <boost/lexical_cast.hpp>
int main()
{
unsigned int i;
try
{
int d =-23;
i = boost::numeric_cast<unsigned int>(d);
}
catch (const boost::numeric::bad_numeric_cast& e)
{
std::cout << e.what() << std::endl;
}
std::cout << i << std::endl; // 4294967273
try
{
char c[] = "-23";
i = boost::lexical_cast<unsigned int>(c);
}
catch (const boost::bad_lexical_cast& e)
{
std::cout << e.what() << std::endl;
}
std::cout << i << std::endl; // 4294967273
return 0;
}
You could write what you want using a modicum of Spirit:
Live On Coliru
#include <boost/spirit/include/qi.hpp>
#include <iostream>
template <typename Out, typename In> Out numeric_lexical_cast(In const& range) {
Out value;
{
using namespace boost::spirit::qi;
using std::begin;
using std::end;
if (!parse(begin(range), end(range), auto_ >> eoi, value)) {
struct bad_numeric_lexical_cast : std::domain_error {
bad_numeric_lexical_cast() : std::domain_error("bad_numeric_lexical_cast") {}
};
throw bad_numeric_lexical_cast();
}
}
return value;
}
int main()
{
for (std::string const& input : { "23", "-23" }) try {
std::cout << " == input: " << input << " -> ";
auto i = numeric_lexical_cast<unsigned int>(input);
std::cout << i << std::endl;
} catch (std::exception const& e) {
std::cout << e.what() << std::endl;
}
}
Prints
== input: 23 -> 23
== input: -23 -> bad_numeric_lexical_cast

Cascade Poco Exception

I try to cascade exception in Poco.
void debug() {
try {
...
xmlFile.parseDocument(*_sim);
...
}
} catch (Poco::Exception& error) {
std::cout << "I'm here" << endl;
std::cout << "Error : " << error.displayText() << std::endl;
}
}
void XMLParser::parseDocument(Manager &manager) {
...
try {
Poco::XML::NodeList* policyList = root->childNodes();
for (uint node=0; node < policyList->length(); node++)
if (policyList->item(node)->hasChildNodes())
manager.insertRule(parseRule(node, policyList->item(node)));
} catch(Poco::Exception& error) {
std::cout << "Error : " << error.displayText() << std::endl;
error.rethrow();
}
}
Rule* XMLParser::parseRule(int flowID, Poco::XML::Node* rule) throw() {
....
if (tLink._srcPort < 0)
throw new Poco::Exception("Source Port isn't valid");
....
}
The deepest exception are thrown, but it does not continue to outer functions.
The program is terminated. Why?
You throw a Poco::Exception pointer so you can not catch it by reference.
Remove 'new'. This should work:
....
if (tLink._srcPort < 0)
throw Poco::Exception("Source Port isn't valid");
....

The std::future_error code() doesn't match its what()

Following Kerrek's guide in What is std::promise?. I try similar sample codes but it doesn't achieve what I expect.
That is, the caught future_errc error's member function code() doesn't match its what(). Exactly speaking, the call code() returns correctly and what() returns the information of next bit of code(). I doubt that this is something wrong in Visual Studio 2012.
Sample codes:
std::future<int> test_future_error1()
{
std::promise<int> prom;
std::future<int> fu = prom.get_future();
prom.set_value(5566);
return fu;
}
//---------------------------------------------------------------
std::future<int> test_future_error2()
{
std::promise<int> prom;
std::future<int> fu = prom.get_future();
std::future<int> fu2 = prom.get_future(); // throw std::future_errc::future_already_retrieved
prom.set_value(5566);
return fu;
}
//---------------------------------------------------------------
std::future<int> test_future_error3()
{
std::promise<int> prom;
std::future<int> fu = prom.get_future();
prom.set_value(5566);
prom.set_value(7788); // throw std::future_errc::promise_already_satisfied
return fu;
}
//---------------------------------------------------------------
std::future<int> test_future_error4()
{
std::promise<int> prom;
std::future<int> fu = prom.get_future();
return fu;
} // throw std::future_errc::broken_promise at fu.get()
//---------------------------------------------------------------
std::future<int> test_future_error5()
{
std::future<int> fu;
return fu;
} // throw std::future_errc::no_state at fu.get()
//---------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
try {
std::future<int> fu = test_future_error3();
int a = fu.get();
std::cout << "a= " << a << std::endl;
} catch(const std::future_error &e) {
std::cout << "future_error:" << std::endl;
if( e.code() == std::future_errc::broken_promise )
std::cout << "code() == std::future_errc::broken_promise" << std::endl;
else if( e.code() == std::future_errc::future_already_retrieved )
std::cout << "code() == std::future_errc::future_already_retrieved" << std::endl;
else if( e.code() == std::future_errc::promise_already_satisfied )
std::cout << "code() == std::future_errc::promise_already_satisfied" << std::endl;
else if( e.code() == std::future_errc::no_state )
std::cout << "code() == std::future_errc::no_state" << std::endl;
else
std::cout << "code() == unknown" << std::endl;
std::cout << "what() == " << e.what() << std::endl;
} catch(const std::exception &e) {
std::cout << "excepton: " << e.what() << std::endl;
}
std::system("pause");
return 0;
}
Result:
future_error:
code() == std::future_errc::promise_already_satisfied
what() == no state

Berkeley DB, concurrent queues

I'm trying to implement a concurrent persistent queue using Berkeley DB. As a starter I tried to make two process which both appends to the DB:
#include <unistd.h>
#include <sstream>
#include <db_cxx.h>
class Queue : public DbEnv
{
public:
Queue ( ) :
DbEnv(0),
db(0)
{
set_flags(DB_CDB_ALLDB, 1);
open("/tmp/db", DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_TXN |
DB_INIT_MPOOL |
DB_RECOVER |
DB_CREATE |
DB_THREAD,
0);
db = new Db(this, 0);
db->set_flags(DB_RENUMBER);
db->open(NULL, "db", NULL, DB_RECNO, DB_CREATE | DB_AUTO_COMMIT | DB_THREAD, 0);
}
virtual ~Queue ()
{
db->close(0);
delete db;
close(0);
}
protected:
Db * db;
};
class Enqueue : public Queue
{
public:
Enqueue ( ) : Queue() { }
virtual ~Enqueue () { }
bool push(const std::string& s)
{
int res;
DbTxn * txn;
try {
txn_begin(NULL, &txn, DB_TXN_SYNC | DB_TXN_WAIT );
db_recno_t k0[4]; // not sure how mutch data is needs???
k0[0] = 0;
Dbt val((void*)s.c_str(), s.length());
Dbt key((void*)&k0, sizeof(k0[0]));
key.set_ulen(sizeof(k0));
key.set_flags(DB_DBT_USERMEM);
res = db->put(txn, &key, &val, DB_APPEND);
if( res == 0 ) {
txn->commit(0);
return true;
} else {
std::cerr << "push failed: " << res << std::endl;
txn->abort();
return false;
}
} catch( DbException e) {
std::cerr << "DB What()" << e.what() << std::endl;
txn->abort();
return false;
} catch( std::exception e) {
std::cerr << "What()" << e.what() << std::endl;
txn->abort();
return false;
} catch(...) {
std::cerr << "Unknown error" << std::endl;
txn->abort();
return false;
}
}
};
using namespace std;
int main(int argc, const char *argv[])
{
fork();
Enqueue e;
stringstream ss;
for(int i = 0; i < 10; i++){
ss.str("");
ss << "asdf" << i;
cout << ss.str() << endl;
if( ! e.push(ss.str()) )
break;
}
return 0;
}
Compiling it:
g++ test.cxx -I/usr/include/db4.8 -ldb_cxx-4.8
Create the db-dir
mkdir /tmp/db
And when I run it I get all kind of errors (segmentations fault, allocation error, and some times it actually works)
I'm sure that I have missed some locking, but I just do not know how to do it. So, any hints and/or suggestions to fix this are most welcome.
Just for the record, here is the solution I have settled on after much googleing and trial'n'error.
The application is a call home process, where the producer is adding data, and consumer tries to send it home. If the consumer fails to send it home, it must try again. The database must not block for producer while the consumer is trying to sink data.
The code has a file lock, and will only allow one consumer process.
Here are the code:
#include <db_cxx.h>
#include <sstream>
#include <fstream>
#include <vector>
#include <boost/interprocess/sync/file_lock.hpp>
class Queue : public DbEnv
{
public:
Queue ( bool sync ) :
DbEnv(0),
db(0)
{
set_flags(DB_CDB_ALLDB, 1);
if( sync )
set_flags(DB_TXN_NOSYNC, 0);
else
set_flags(DB_TXN_NOSYNC, 1);
open("/tmp/db", DB_INIT_LOCK |
DB_INIT_LOG | DB_INIT_TXN | DB_INIT_MPOOL |
DB_REGISTER | DB_RECOVER | DB_CREATE | DB_THREAD,
0);
db = new Db(this, 0);
db->set_flags(DB_RENUMBER);
db->open(NULL, "db", NULL, DB_RECNO, DB_CREATE | DB_AUTO_COMMIT | DB_THREAD, 0);
}
virtual ~Queue ()
{
db->close(0);
delete db;
close(0);
}
protected:
Db * db;
};
struct Transaction
{
Transaction() : t(0) { }
bool init(DbEnv * dbenv ){
try {
dbenv->txn_begin(NULL, &t, 0);
} catch( DbException e) {
std::cerr << "DB What()" << e.what() << std::endl;
return false;
} catch( std::exception e) {
std::cerr << "What()" << e.what() << std::endl;
return false;
} catch(...) {
std::cerr << "Unknown error" << std::endl;
return false;
}
return true;
}
~Transaction(){ if( t!=0) t->abort(); }
void abort() { t->abort(); t = 0; }
void commit() { t->commit(0); t = 0; }
DbTxn * t;
};
struct Cursor
{
Cursor() : c(0) { }
bool init( Db * db, DbTxn * t) {
try {
db->cursor(t, &c, 0);
} catch( DbException e) {
std::cerr << "DB What()" << e.what() << std::endl;
return false;
} catch( std::exception e) {
std::cerr << "What()" << e.what() << std::endl;
return false;
} catch(...) {
std::cerr << "Unknown error" << std::endl;
return false;
}
return true;
}
~Cursor(){ if( c!=0) c->close(); }
void close(){ c->close(); c = 0; }
Dbc * c;
};
class Enqueue : public Queue
{
public:
Enqueue ( bool sync ) : Queue(sync) { }
virtual ~Enqueue () { }
bool push(const std::string& s)
{
int res;
Transaction transaction;
if( ! transaction.init(this) )
return false;
try {
db_recno_t k0[4]; // not sure how mutch data is needs???
k0[0] = 0;
Dbt val((void*)s.c_str(), s.length());
Dbt key((void*)&k0, sizeof(k0[0]));
key.set_ulen(sizeof(k0));
key.set_flags(DB_DBT_USERMEM);
res = db->put(transaction.t, &key, &val, DB_APPEND);
if( res == 0 ) {
transaction.commit();
return true;
} else {
std::cerr << "push failed: " << res << std::endl;
return false;
}
} catch( DbException e) {
std::cerr << "DB What()" << e.what() << std::endl;
return false;
} catch( std::exception e) {
std::cerr << "What()" << e.what() << std::endl;
return false;
} catch(...) {
std::cerr << "Unknown error" << std::endl;
return false;
}
}
};
const char * create_file(const char * f ){
std::ofstream _f;
_f.open(f, std::ios::out);
_f.close();
return f;
}
class Dequeue : public Queue
{
public:
Dequeue ( bool sync ) :
Queue(sync),
lock(create_file("/tmp/db-test-pop.lock")),
number_of_records_(0)
{
std::cout << "Trying to get exclusize access to database" << std::endl;
lock.lock();
}
virtual ~Dequeue ()
{
}
bool pop(size_t number_of_records, std::vector<std::string>& records)
{
if( number_of_records_ != 0 ) // TODO, warning
abort();
Cursor cursor;
records.clear();
if( number_of_records_ != 0 )
abort(); // TODO, warning
// Get a cursor
try {
db->cursor(0, &cursor.c, 0);
} catch( DbException e) {
std::cerr << "DB What()" << e.what() << std::endl;
abort();
return false;
}
// Read and delete
try {
Dbt val;
db_recno_t k0 = 0;
Dbt key((void*)&k0, sizeof(k0));
for( size_t i = 0; i < number_of_records; i ++ ) {
int get_res = cursor.c->get(&key, &val, DB_NEXT);
if( get_res == 0 )
records.push_back(std::string((char *)val.get_data(), val.get_size()));
else
break;
}
number_of_records_ = records.size();
if( number_of_records_ == 0 ) {
abort();
return false;
} else {
return true;
}
} catch( DbException e) {
std::cerr << "DB read/delete What() " << e.what() << std::endl;
abort();
return false;
} catch( std::exception e) {
std::cerr << "DB read/delete What() " << e.what() << std::endl;
abort();
return false;
}
}
bool commit()
{
if( number_of_records_ == 0 )
return true;
Transaction transaction;
Cursor cursor;
if( ! transaction.init(this) )
return false;
if( ! cursor.init(db, transaction.t) )
return false;
// Read and delete
try {
Dbt val;
db_recno_t k0 = 0;
Dbt key((void*)&k0, sizeof(k0));
for( size_t i = 0; i < number_of_records_; i ++ ) {
int get_res = cursor.c->get(&key, &val, DB_NEXT);
if( get_res == 0 )
cursor.c->del(0);
else
break; // this is bad!
}
number_of_records_ = 0;
cursor.close();
transaction.commit();
return true;
} catch( DbException e) {
std::cerr << "DB read/delete What() " << e.what() << std::endl;
return false;
} catch( std::exception e) {
std::cerr << "DB read/delete What() " << e.what() << std::endl;
return false;
}
}
void abort()
{
number_of_records_ = 0;
}
private:
boost::interprocess::file_lock lock;
size_t number_of_records_;
sigset_t orig_mask;
};
Please let me know if you see any errors, or if know about an easier way to do this.