FAQ 26.08 Should destructors call routines that may throw exceptions?

Yes, provided the destructor catches whatever the routines might throw.

If a destructor is called while unwinding the stack caused by another exception, and that destructor calls a routine f() that throws an exception, the destructor must catch the second (nested) exception; otherwise the exception-handling mechanism calls the terminate() function. In plain English: if the destructor calls something that might throw an exception, the destructor should catch all possible exceptions.

 #include <iostream> #include <stdexcept> using namespace std; void fred() throw(runtime_error) {   cout << "fred() throwing\n";   throw runtime_error("thrown from fred()"); } class X { public:   ~X() throw(); }; X::~X() throw() {   try {     fred();   }   catch (exception& e) {     cout << "handling fred()'s exception: " << e.what() << '\n';   } } int main() {   try {     X x;     cout << "main() throwing\n";     throw logic_error("thrown from main()");   }   catch (exception& e) {     cout << "handling main()'s exception: " << e.what() << '\n';   } } 

X::~X() is called as a result of the exception thrown by main(). But X::~X() calls fred(), which also throws an exception. Fortunately X::~X() catches the exception thrown by fred(); otherwise terminate() would be called at the end of X::~X().

The output is

 main() throwing fred() throwing handling fred()'s exception: thrown from fred() handling main()'s exception: thrown from main() 


C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net