?? ch20.htm
字號:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<!-- This document was created from RTF source by rtftohtml version 3.0.1 -->
<META NAME="GENERATOR" Content="Symantec Visual Page 1.0">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1">
<TITLE>Teach Yourself C++ in 21 Days</TITLE>
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#FFFFFF">
<H1 ALIGN="CENTER"><A HREF="ch19.htm" tppabs="http://petunia.atomki.hu/pio/Manuals/english/0-672/0-672-31070-8/htm/ch19.htm"><IMG SRC="../buttons/BLANPREV.GIF" tppabs="http://petunia.atomki.hu/pio/Manuals/english/0-672/0-672-31070-8/buttons/BLANPREV.GIF"
WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="javascript:if(confirm('http://www.mcp.com/sams \n\nThis file was not retrieved by Teleport Pro, because it is addressed on a domain or path outside the boundaries set for its Starting Address. \n\nDo you want to open it from the server?'))window.location='http://www.mcp.com/sams'" tppabs="http://www.mcp.com/sams"><IMG
SRC="../buttons/BLANHOME.GIF" tppabs="http://petunia.atomki.hu/pio/Manuals/english/0-672/0-672-31070-8/buttons/BLANHOME.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM"
BORDER="0"></A><A HREF="../index.htm" tppabs="http://petunia.atomki.hu/pio/Manuals/english/0-672/0-672-31070-8/index.htm"><IMG SRC="../buttons/BLANTOC.GIF" tppabs="http://petunia.atomki.hu/pio/Manuals/english/0-672/0-672-31070-8/buttons/BLANTOC.GIF"
WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="ch21.htm" tppabs="http://petunia.atomki.hu/pio/Manuals/english/0-672/0-672-31070-8/htm/ch21.htm"><IMG SRC="../buttons/BLANNEXT.GIF" tppabs="http://petunia.atomki.hu/pio/Manuals/english/0-672/0-672-31070-8/buttons/BLANNEXT.GIF"
WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A></H1>
<H1></H1>
<UL>
<LI><A HREF="#Heading1">Day 20</A>
<UL>
<LI><A HREF="#Heading2">Exceptions and Error Handling</A>
<UL>
<LI><A HREF="#Heading3">Bugs, Errors, Mistakes, and Code Rot</A>
<UL>
<LI><A HREF="#Heading4">Exceptions</A>
<LI><A HREF="#Heading5">A Word About Code Rot</A>
</UL>
<LI><A HREF="#Heading6">Exceptions</A>
<UL>
<LI><A HREF="#Heading7">How Exceptions Are Used</A>
</UL>
<LI><A HREF="#Heading8">Listing 20.1. Raising an exception.</A>
<LI><A HREF="#Heading9">try Blocks</A>
<LI><A HREF="#Heading10">catch Blocks</A>
<LI><A HREF="#Heading11">Using try Blocks and catch Blocks</A>
<UL>
<LI><A HREF="#Heading12">Catching Exceptions</A>
<LI><A HREF="#Heading13">More Than One catch Specification</A>
</UL>
<LI><A HREF="#Heading14">Listing 20.2. Multiple exceptions.</A>
<UL>
<LI><A HREF="#Heading15">Exception Hierarchies</A>
</UL>
<LI><A HREF="#Heading16">Listing 20.3. Class hierarchies and exceptions</A><A HREF="#Heading17">.</A>
<LI><A HREF="#Heading18">Data in Exceptions and Naming Exception Objects</A>
<LI><A HREF="#Heading19">Listing 20.4. Getting data out of an exception object</A><A
HREF="#Heading20">.</A>
<LI><A HREF="#Heading21">Listing 20.5.</A>
<LI><A HREF="#Heading22">Passing by reference and using virtual functions in exceptions.</A>
<LI><A HREF="#Heading23">Exceptions and Templates</A>
<LI><A HREF="#Heading24">Listing 20.6. Using exceptions with templates.</A>
<LI><A HREF="#Heading25">Exceptions Without Errors</A>
<LI><A HREF="#Heading26">Bugs and Debugging</A>
<UL>
<LI><A HREF="#Heading27">Breakpoints</A>
<LI><A HREF="#Heading28">Watch Points</A>
<LI><A HREF="#Heading29">Examining Memory</A>
<LI><A HREF="#Heading30">Assembler</A>
</UL>
<LI><A HREF="#Heading31">Summary</A>
<LI><A HREF="#Heading32">Q&A</A>
<LI><A HREF="#Heading33">Workshop</A>
<UL>
<LI><A HREF="#Heading34">Quiz</A>
<LI><A HREF="#Heading35">Exercises</A>
</UL>
</UL>
</UL>
</UL>
<P>
<HR SIZE="4">
<H2 ALIGN="CENTER"><A NAME="Heading1"></A><FONT COLOR="#000077">Day 20</FONT></H2>
<H2 ALIGN="CENTER"><A NAME="Heading2"></A><FONT COLOR="#000077">Exceptions and Error
Handling</FONT></H2>
<P>The code you've seen in this book has been created for illustration purposes.
It has not dealt with errors so that you would not be distracted from the central
issues being presented. Real-world programs must take error conditions into consideration.</P>
<P>Today you will learn
<UL>
<LI>What exceptions are.
<P>
<LI>How exceptions are used, and what issues they raise.
<P>
<LI>How to build exception hierarchies.
<P>
<LI>How exceptions fit into an overall error-handling approach.
<P>
<LI>What a debugger is.
</UL>
<H3 ALIGN="CENTER"><A NAME="Heading3"></A><FONT COLOR="#000077">Bugs, Errors, Mistakes,
and Code Rot</FONT></H3>
<P>All programs have bugs. The bigger the program, the more bugs, and many of those
bugs actually "get out the door" and into final, released software. That
this is true does not make it okay, and making robust, bug-free programs is the number-one
priority of anyone serious about programming.</P>
<P>The single biggest problem in the software industry is buggy, unstable code. The
biggest expense in many major programming efforts is testing and fixing. The person
who solves the problem of producing good, solid, bulletproof programs at low cost
and on time will revolutionize the software industry.</P>
<P>There are a number of discrete kinds of bugs that can trouble a program. The first
is poor logic: The program does just what you asked, but you haven't thought through
the algorithms properly. The second is syntactic: You used the wrong idiom, function,
or structure. These two are the most common, and they are the ones most programmers
are on the lookout for.</P>
<P>Research and real-world experience have shown beyond a doubt that the later in
the development process you find a problem, the more it costs to fix it. The least
expensive problems or bugs to fix are the ones you manage to avoid creating. The
next cheapest are those the compiler spots. The C++ standards force compilers to
put a lot of energy into making more and more bugs show up at compile time.</P>
<P>Bugs that get compiled in but are caught at the first test--those that crash every
time--are less expensive to find and fix than those that are flaky and only crash
once in a while.</P>
<P>A bigger problem than logic or syntactic bugs is unnecessary fragility: Your program
works just fine if the user enters a number when you ask for one, but it crashes
if the user enters letters. Other programs crash if they run out of memory, or if
the floppy disk is left out of the drive, or if the modem drops the line.</P>
<P>To combat this kind of fragility, programmers strive to make their programs bulletproof.
A bulletproof program is one that can handle anything that comes up at runtime, from
bizarre user input to running out of memory.</P>
<P>It is important to distinguish between bugs, which arise because the programmer
made a mistake in syntax; logic errors, which arise because the programmer misunderstood
the problem or how to solve it; and exceptions, which arise because of unusual but
predictable problems such as running out of resources (memory or disk space).
<H4 ALIGN="CENTER"><A NAME="Heading4"></A><FONT COLOR="#000077">Exceptions</FONT></H4>
<P>Programmers use powerful compilers and sprinkle their code with <TT>assert</TT>s,
as discussed on Day 17, "The Preprocessor," to catch programming errors.
They use design reviews and exhaustive testing to find logic errors.</P>
<P>Exceptions are different, however. You can't eliminate exceptional circumstances;
you can only prepare for them. Your users will run out of memory from time to time,
and the only question is what you will do. Your choices are limited to these:
<UL>
<LI>Crash the program.
<P>
<LI>Inform the user and exit gracefully.
<P>
<LI>Inform the user and allow the user to try to recover and continue.
<P>
<LI>Take corrective action and continue without disturbing the user.
</UL>
<P>While it is not necessary or even desirable for every program you write to automatically
and silently recover from all exceptional circumstances, it is clear that you must
do better than crashing.</P>
<P>C++ exception handling provides a type-safe, integrated method for coping with
the predictable but unusual conditions that arise while running a program.
<H4 ALIGN="CENTER"><A NAME="Heading5"></A><FONT COLOR="#000077">A Word About Code
Rot</FONT></H4>
<P>Code rot is a well-proven phenomenon. Code rot is when code deteriorates due to
being neglected. Perfectly well-written, fully debugged code will develop new and
bizarre behavior six months after you release it, and there isn't much you can do
to stop it. What you can do, of course, is write your programs so that when you go
back to fix the spoilage, you can quickly and easily identify where the problems
are.
<BLOCKQUOTE>
<P>
<HR>
<FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Code rot is somewhat of a programmer's
joke used to explain how bug-free code suddenly becomes unreliable. It does, however,
teach an important lesson. Programs are enormously complex, and bugs, errors, and
mistakes can hide for a long time before turning up. Protect yourself by writing
easy-to-maintain code.
<HR>
</BLOCKQUOTE>
<P>This means that your code must be commented even if you don't expect anyone else
to ever look at it. Six months after you deliver your code, you will read it with
the eyes of a total stranger, bewildered by how anyone could ever have written such
convoluted and twisty code and expected anything but disaster.
<H3 ALIGN="CENTER"><A NAME="Heading6"></A><FONT COLOR="#000077">Exceptions</FONT></H3>
<P>In C++, an exception is an object that is passed from the area of code where a
problem occurs to the part of the code that is going to handle the problem. The type
of the exception determines which area of code will handle the problem, and the contents
of the object thrown, if any, may be used to provide feedback to the user.</P>
<P>The basic idea behind exceptions is fairly straightforward:
<UL>
<LI>The actual allocation of resources (for example, the allocation of memory or
the locking of a file) is usually done at a very low level in the program.
<P>
<LI>The logic of what to do when an operation fails, memory cannot be allocated,
or a file cannot be locked is usually high in the program, with the code for interacting
with the user.
<P>
<LI>Exceptions provide an express path from the code that allocates resources to
the code that can handle the error condition. If there are intervening layers of
functions, they are given an opportunity to clean up memory allocations, but are
not required to include code whose only purpose is to pass along the error condition.
</UL>
<H4 ALIGN="CENTER"><A NAME="Heading7"></A><FONT COLOR="#000077">How Exceptions Are
Used</FONT></H4>
<P><TT>try</TT> blocks are created to surround areas of code that may have a problem.
For example:</P>
<PRE><FONT COLOR="#0066FF">try
{
SomeDangerousFunction();
}
</FONT></PRE>
<P><TT>catch</TT> blocks handle the exceptions thrown in the <TT>try</TT> block.
For example:</P>
<PRE><FONT COLOR="#0066FF">try
{
SomeDangerousFunction();
}
catch(OutOfMemory)
{
// take some actions
}
catch(FileNotFound)
{
// take other action
}
</FONT></PRE>
<P>The basic steps in using exceptions are
<DL>
<DD><B>1.</B> Identify those areas of the program in which you begin an operation
that might raise an exception, and put them in <TT>try</TT> blocks.<BR>
<BR>
<B>2.</B> Create <TT>catch</TT> blocks to catch the exceptions if they are thrown,
to clean up allocated memory, and to inform the user as appropriate. Listing 20.1
illustrates the use of both <TT>try</TT> blocks and <TT>catch</TT> blocks.<BR>
<B><BR>
</B>
<HR>
<FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B><I>Exceptions </I>are objects
used to transmit information about a problem.
<HR>
<P>
<HR>
<FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>try block </I>is a block
surrounded by braces in which an exception may be thrown.
<HR>
</P>
<P>
<HR>
<FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>catch block</I> is the
block immediately following a <TT>try</TT> block, in which exceptions are handled.</P>
<P>When an exception is thrown (or raised), control transfers to the <TT>catch</TT>
block immediately following the current <TT>try</TT> block.
<HR>
</DL>
<BLOCKQUOTE>
<P>
<HR>
<FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Some older compilers do not support
exceptions. Exceptions are, however, part of the emerging C++ standard. All major
compiler vendors have committed to supporting exceptions in their next releases,
if they have not already done so. If you have an older compiler, you won't be able
to compile and run the exercises in this chapter. It's still a good idea to read
through the entire chapter, however, and return to this material when you upgrade
your compiler.
<HR>
</BLOCKQUOTE>
<P><A NAME="Heading8"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 20.1. Raising
an exception.</B></FONT>
<PRE><FONT COLOR="#0066FF">0: #include <iostream.h>
1:
2: const int DefaultSize = 10;
3:
4: class Array
5: {
6: public:
7: // constructors
8: Array(int itsSize = DefaultSize);
9: Array(const Array &rhs);
10: ~Array() { delete [] pType;}
11:
12: // operators
13: Array& operator=(const Array&);
14: int& operator[](int offSet);
15: const int& operator[](int offSet) const;
16:
17: // accessors
18: int GetitsSize() const { return itsSize; }
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -