Exception Handling with Pointers and the new Operator


From the beginning of C++, there have been several different ways to handle the failure of the new operator. Therefore any code you read may include several different approaches to handling this failure. A previous version of C++ called exceptions of type xalloc. While Standard C++ has a different technique designed for this type of procedure, your compiler may still be using xalloc or one of the other earlier techniques. You should check your compiler's manual to determine which method to use.

In Standard C++ ever call to the new operator should be enclosed in a try{} block. An exception of the new operator throws an exception of type: bad_alloc. If you do not catch() this exception, then the program will terminate. To use this type of exception your code must have the preprocessor statement: #include<new> and provide for a catch() that has the following construct:

image from book

 Try {   thePointer = new SomeType;   ...... } catch(bad_alloc an_object) {    ........ } 

image from book

where thePointer is a pointer to the data type: SomeType that is the type of data being allocated by the new operator.

If you are replacing code that was written in C where malloc() was used, it is recommend that you follow a different approach. In this case you should use a different form of the new operator that has an argument. The argument should be nothrow. This version of new will return null as was the case in some earlier versions of C++. This could be handled in the following manner:

image from book

 ptr = new(nothrow) some_type; if(!ptr) {     ........ } 

image from book




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

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