11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

332Part V: Optional FeaturesThis mechanism has several problems: It’s highly repetitive. It forces the user to invent and keep track of numerous error returnindications. It mixes the error-handling code into the normal code flow, therebyobscuring the normal, non-error path.These problems don’t seem so bad in this simple example, but they becomeincreasingly worse as the calling code becomes more complex. The result isthat error-handling code doesn’t get written to handle all the conditions thatit should.The exception mechanism addresses these problems by removing the errorpath from the normal code path. Furthermore, exceptions make error handlingobligatory. If your function doesn’t handle the thrown exception, controlpasses up the chain of called functions until C++ finds a function to handle theerror. This also gives you the flexibility to ignore errors that you can’t do anythingabout anyway. Only the functions that can actually correct the problemneed to catch the exception.Examining the Exception MechanismTake a closer look at the steps that the code goes through to handle an exception.When the throw occurs, C++ first copies the thrown object to some neutralplace. It then begins looking for the end of the current try block.If a try block is not found in the current function, control passes to the callingfunction. A search is then made of that function. If no try block is found there,control passes to the function that called it, and so on up the stack of callingfunctions. This process is called unwinding the stack.An important feature of stack unwinding is that as each stack is unwound,objects that go out of scope are destructed just as though the function hadexecuted a return statement. This keeps the program from losing assets orleaving objects dangling.When the encasing try block is found, the code searches the first catch phraseimmediately following the closing brace of the catch block. If the object thrownmatches the type of argument specified in the catch statement, control passesto that catch phrase. If not, a check is made of the next catch phrase. If nomatching catch phrases are found, the code searches for the next higher leveltry block in an ever-outward spiral until an appropriate catch can be found. Ifno catch phrase is found, the program is terminated.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!