⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch20.htm

📁 一本好的VC学习书,本人就是使用这本书开始学习的vc,希望能对大家有帮助
💻 HTM
📖 第 1 页 / 共 5 页
字号:
<!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://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch19.htm"><IMG SRC="BLANPREV.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANPREV.GIF"WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="tppmsgs/msgs0.htm#1" tppabs="http://www.mcp.com/sams"><IMGSRC="BLANHOME.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANHOME.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM"BORDER="0"></A><A HREF="index.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/index.htm"><IMG SRC="BLANTOC.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANTOC.GIF"WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="ch21.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch21.htm"><IMG SRC="BLANNEXT.GIF" tppabs="http://www.mcp.com/814147200/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&amp;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 ErrorHandling</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 centralissues 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 thosebugs actually &quot;get out the door&quot; and into final, released software. Thatthis is true does not make it okay, and making robust, bug-free programs is the number-onepriority of anyone serious about programming.</P><P>The single biggest problem in the software industry is buggy, unstable code. Thebiggest expense in many major programming efforts is testing and fixing. The personwho solves the problem of producing good, solid, bulletproof programs at low costand on time will revolutionize the software industry.</P><P>There are a number of discrete kinds of bugs that can trouble a program. The firstis poor logic: The program does just what you asked, but you haven't thought throughthe 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 programmersare on the lookout for.</P><P>Research and real-world experience have shown beyond a doubt that the later inthe development process you find a problem, the more it costs to fix it. The leastexpensive problems or bugs to fix are the ones you manage to avoid creating. Thenext cheapest are those the compiler spots. The C++ standards force compilers toput 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 everytime--are less expensive to find and fix than those that are flaky and only crashonce in a while.</P><P>A bigger problem than logic or syntactic bugs is unnecessary fragility: Your programworks just fine if the user enters a number when you ask for one, but it crashesif the user enters letters. Other programs crash if they run out of memory, or ifthe 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, frombizarre user input to running out of memory.</P><P>It is important to distinguish between bugs, which arise because the programmermade a mistake in syntax; logic errors, which arise because the programmer misunderstoodthe problem or how to solve it; and exceptions, which arise because of unusual butpredictable 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, &quot;The Preprocessor,&quot; 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 automaticallyand silently recover from all exceptional circumstances, it is clear that you mustdo better than crashing.</P><P>C++ exception handling provides a type-safe, integrated method for coping withthe predictable but unusual conditions that arise while running a program.<H4 ALIGN="CENTER"><A NAME="Heading5"></A><FONT COLOR="#000077">A Word About CodeRot</FONT></H4><P>Code rot is a well-proven phenomenon. Code rot is when code deteriorates due tobeing neglected. Perfectly well-written, fully debugged code will develop new andbizarre behavior six months after you release it, and there isn't much you can doto stop it. What you can do, of course, is write your programs so that when you goback to fix the spoilage, you can quickly and easily identify where the problemsare.<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 elseto ever look at it. Six months after you deliver your code, you will read it withthe eyes of a total stranger, bewildered by how anyone could ever have written suchconvoluted 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 aproblem occurs to the part of the code that is going to handle the problem. The typeof the exception determines which area of code will handle the problem, and the contentsof 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 AreUsed</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. Raisingan exception.</B></FONT><PRE><FONT COLOR="#0066FF">0:       #include &lt;iostream.h&gt;1:    2:       const int DefaultSize = 10;3:    4:       class Array5:       {6:       public:7:          // constructors8:          Array(int itsSize = DefaultSize);9:          Array(const Array &amp;rhs);10:          ~Array() { delete [] pType;}11:    12:          // operators13:          Array&amp; operator=(const Array&amp;);14:          int&amp; operator[](int offSet);15:          const int&amp; operator[](int offSet) const;16:    17:          // accessors18:          int GetitsSize() const { return itsSize; }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -