FAQ 12.07 How can new be convinced to return NULL rather than throw an exception?

FAQ 12.07 How can new be convinced to return NULL rather than throw an exception?

graphics/new_icon.gif

Replace new Fred() with new(nothrow) Fred(). Note that this is a step backward for the reasons already described, so this technique should not be extensively used in new C++ code. However this technique is relevant for people who have to deal with C++ software that was written before new Fred() threw exceptions.

When preexception C++ code is compiled on a modern C++ compiler, the use of exceptions may cause the application to crash. In this case, there are two basic options: update the application by making it exception safe (that is, make the code do something reasonable even if something such as new throws an exception), or patch the application by replacing new Fred() with new(nothrow) Fred(). Often, but not always, it is cheaper to patch it rather than make it exception safe. The following example demonstrates this technique.

 #include <new> using namespace std; void sample() throw() {   Fred* p = new(nothrow) Fred();                     <-- 1   if (p == NULL) {                                   <-- 2     // ...   } } 

(1) Note the nothrow

(2) This test is required!



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