right usage of std::uncaught_exception in a destructor
Posted
by Vokuhila-Oliba
on Stack Overflow
See other posts from Stack Overflow
or by Vokuhila-Oliba
Published on 2010-03-19T05:24:11Z
Indexed on
2010/03/19
5:31 UTC
Read the original article
Hit count: 368
There are some articles concluding "never throw an exception from a destructor", and "std::uncaught_exception() is not useful", for example:
- http://www.gotw.ca/gotw/047.htm (written by Herb Sutter)
But it seems that I am not getting the point. So I wrote a small testing example (see below).
Since everything is fine with the testing example I would very appreciate some comments regarding what might be wrong with it.
testing results:
./main
Foo::~Foo(): caught exception - but have pending exception - ignoring
int main(int, char**): caught exception: from int Foo::bar(int)
./main 1
Foo::~Foo(): caught exception - but *no* exception is pending - rethrowing
int main(int, char**): caught exception: from Foo::~Foo()
// file main.cpp
// build with e.g. "make main"
// tested successfully on Ubuntu-Karmic with g++ v4.4.1
#include <iostream>
class Foo {
public:
int bar(int i) {
if (0 == i)
throw(std::string("from ") + __PRETTY_FUNCTION__);
else
return i+1;
}
~Foo() {
bool exc_pending=std::uncaught_exception();
try {
bar(0);
} catch (const std::string &e) {
// ensure that no new exception has been created in the meantime
if (std::uncaught_exception()) exc_pending = true;
if (exc_pending) {
std::cerr << __PRETTY_FUNCTION__
<< ": caught exception - but have pending exception - ignoring"
<< std::endl;
} else {
std::cerr << __PRETTY_FUNCTION__
<< ": caught exception - but *no* exception is pending - rethrowing"
<< std::endl;
throw(std::string("from ") + __PRETTY_FUNCTION__);
}
}
}
};
int main(int argc, char** argv) {
try {
Foo f;
// will throw an exception in Foo::bar() if no arguments given. Otherwise
// an exception from Foo::~Foo() is thrown.
f.bar(argc-1);
} catch (const std::string &e) {
std::cerr << __PRETTY_FUNCTION__ << ": caught exception: " << e << std::endl;
}
return 0;
}
© Stack Overflow or respective owner