[ Pobierz całość w formacie PDF ]
//a function is violatedAll standard exceptions have provided the member function what(), which returns a const
char * with an implementation-dependent verbal description of the exception. Note, however, that the standard
library has an additional set of exceptions that are thrown by its components.
Exception Handlers Hierarchy
Exceptions are caught in a bottom-down hierarchy: Specific (most derived classes) exceptions are handled first,
followed by groups of exceptions (base classes), and, finally, a catch all handler. For example
#include
#include
using namespace std;
int main()
{
try
{
char * buff = new char[100000000];
//...use buff
}
catch(bad_alloc& alloc_failure) // bad_alloc is
//derived from exception
{
cout
//... handle exception thrown by operator new
}
file:///D|/Cool Stuff/old/ftp/1/1/ch06/ch06.htm (12 von 18) [12.05.2000 14:46:11]
ANSI/ISO C++ Professional Programmer's Handbook - Chapter 6 - Exception Handling
catch(exception& std_ex)
{
cout
}
catch(...) // exceptions that are not handled elsewhere are caught here
{
cout
}
return 0;
}
Handlers of the most derived objects must appear before the handlers of base classes. This is because handlers are
tried in order of appearance. It is therefore possible to write handlers that are never executed, for example, by placing
a handler for a derived class after a handler for a corresponding base class. For example
catch(std::exception& std_ex) //bad_alloc exception is always handled here
{
//...handle the exception
}
catch(std::bad_alloc& alloc_failure) //unreachable
{
cout
}
Rethrowing an Exception
An exception is thrown to indicate an abnormal state. The first handle to catch the exception can try to fix the
problem. If it fails to do so, or if it only manages to perform a partial recovery, it can still rethrow the exception,
thereby letting a higher try block handle it. For that purpose, try blocks can be nested in a hierarchical order,
enabling a rethrown exception from a lower catch statement to be caught again. A rethrow is indicated by a throw
statement without an operand. For example
#include
#include
using namespace std;
enum {SUCCESS, FAILURE};
class File
{
public: File (const char *) {}
public: bool IsValid() const {return false; }
public: int OpenNew() const {return FAILURE; }
};
class Exception {/*..*/}; //general base class for exceptions
class FileException: public Exception
{
public: FileException(const char *p) : s(p) {}
public: const char * Error() const { return s.c_str(); }
private: string s;
};
void func(File& );
int main()
file:///D|/Cool Stuff/old/ftp/1/1/ch06/ch06.htm (13 von 18) [12.05.2000 14:46:11]
ANSI/ISO C++ Professional Programmer's Handbook - Chapter 6 - Exception Handling
{
try //outer try
{
File f ("db.dat");
func; // 1
}
catch(...) // 7
//this handler will catch the re-thrown exception;
//note: the same exception type is required
{
cout
}
return 0;
}
void func(File & f)
{
try //inner try
{
if (f.IsValid() == false )
throw FileException("db.dat"); // 2
}
catch(FileException &fe) // 3
//first chance to cope with the exception
{
cout
if (f.OpenNew() != SUCCESS) (5)
//re-throw the original exception and let a higher handler deal with it
throw; // 6
}
}
In the preceding example, the function func() is called from the try block inside main() (1). The second try
block inside func() throws an exception of type FileException (2). This exception is caught by the catch
block inside func() (3). The catch block attempts to remedy the situation by opening a new file. This attempt
fails (5), and the FileException is rethrown (6). Finally, the rethrown exception is caught -- this time, by the
catch(...) block inside main() (7).
Function try Blocks
A function try block is a function whose body consists of a try block and its associated handlers. A function try
block enables a handler to catch an exception
that is thrown during the execution of the initializer expressions in the constructor's member initialization list or
during the execution of the constructor's body. Note, however, that unlike handlers of ordinary exceptions, the handler
of a function try block merely catches the exception -- it cannot continue the object's construction normally. This is
because the partially constructed object is destroyed as a result of the stack unwinding. In addition, the handler of a
function try block cannot execute a return statement (eventually, the handler must exit by a throw). What is the
use of a function try block then? The handler enables you to throw a different exception than the one that it just
caught, thereby preventing a violation of the exception specification. For example
class X{};
file:///D|/Cool Stuff/old/ftp/1/1/ch06/ch06.htm (14 von 18) [12.05.2000 14:46:11]
ANSI/ISO C++ Professional Programmer's Handbook - Chapter 6 - Exception Handling
C::C(const std::string& s) throw (X) // allowed to throw X only
try
: str(s) // str's constructor might throw a bad_alloc exception,
// might violate C's exception specification
{
// constructor function body
}
catch (...) //handle any exception thrown from ctor initializer or ctor body
{
//...
throw X(); //replace bad_alloc exception with an exception of type X
}
In this example, a string object is first constructed as a member of class C. string might throw a bad_alloc
exception during its construction. The function try block catches the bad_alloc exception and throws instead an
exception of type X, which satisfies the exception specification of C's constructor.
Use auto_ptr to Avoid Memory Leaks
The Standard Library supplies the class template auto_ptr (discussed in Chapter 10, "STL and Generic
Programming"), which automatically deallocates memory that is allocated on the free store in much the same manner
as local objects are reclaimed in case of exiting their scope. When an auto_ptr is instantiated, it can be
initialized with a pointer to an object that is allocated on the free store. When the current scope is exited, the
destructor of the auto_ptr object automatically deletes the object that is bound to it. By using auto_ptr,
you can avoid memory leakage in the case of an exception. Furthermore, auto_ptr can simplify programming
by sparing the bother of explicitly deleting objects that were allocated on the free store. auto_ptr is defined in
the standard header file.
For example
#include
#include
using namespace std;
class Date{ public: const char * DateString(); };
void DisplayDate()
{
//create a local object of type auto_ptr
auto_ptr pd (new Date); //now pd is owned by the template object
cout
//pd is automatically deleted by the destructor of auto_ptr;
}
In the preceding example, the auto_ptr instance, pd, can be used like an ordinary pointer to Date. The
overloaded operators *, ->, and & of auto_ptr provide the pointer-like syntax. pd's bound object is
automatically destroyed when DisplayDate() exits.
Exception Handling Performance Overhead
By nature, exception handling relies heavily on runtime type checking. When an exception is thrown, the
implementation has to determine whether the exception was thrown from a try block (an exception can be thrown
from a program section that is not enclosed within a try block -- by operator new, for example). If indeed the
file:///D|/Cool Stuff/old/ftp/1/1/ch06/ch06.htm (15 von 18) [12.05.2000 14:46:11]
ANSI/ISO C++ Professional Programmer's Handbook - Chapter 6 - Exception Handling
exception was thrown from a try block, the implementation compares the type of the exception and attempts to find
a matching handler in the current scope. If a match is found, control is transferred to the handler's body. This is the
optimistic scenario. What if the implementation cannot find a matching handler for the exception, though, or what if
the exception was not thrown from a try block? In such a case, the current function is unwound from the stack and
the next active function in the stack is entered. The same process is reiterated until a matching handler has been found
(at that point, all the automatic objects that were created on the path from a try block to a throw expression have
[ Pobierz całość w formacie PDF ]
ebook @ pobieranie @ pdf @ do ÂściÂągnięcia @ download
Wątki
- Home
- Flash Professional CS5 Čtěte
- National Goat Handbook
- De La Cruz Melissa BśÂćÂkitnokrwiśÂci Wilczy pakt
- 0775. Gold Kristi Szokujć ce wyznanie
- Gill Judy Desperado
- Carol Look Improve Your Eyesight EFT
- James Axler Deathlands 017 Fury's Pilgrims
- Foley, Gaelen 2 Lord of Ice
- Major Ann Bracia Storm 01 W ogniu milosci
- James C. Glass Shanji
- zanotowane.pl
- doc.pisz.pl
- pdf.pisz.pl
- ministranci-w.xlx.pl
Cytat
Ibi patria, ibi bene. - tam (jest) ojczyzna, gdzie (jest) dobrze
Dla cierpiącego fizycznie potrzebny jest lekarz, dla cierpiącego psychicznie - przyjaciel. Menander
Jak gore, to już nie trza dmuchać. Prymus
De nihilo nihil fit - z niczego nic nie powstaje.
Dies diem doces - dzień uczy dzień.