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

📄 ch26.htm

📁 VC使用大全。里面集合了VC使用的各种使用技巧。非常有用。
💻 HTM
📖 第 1 页 / 共 5 页
字号:
<HTML>

<HEAD>

<TITLE>Special Edition Using Visual C++ 5 - Chapter 26</TITLE>

<LINK REL="Next" HREF="ch27.htm" tppabs="http://www.mcp.com/814147200/0-7897/0-7897-1145-1/ch27.htm">

<LINK REL="Previous" HREF="ch25.htm" tppabs="http://www.mcp.com/814147200/0-7897/0-7897-1145-1/ch25.htm"></HEAD>

<BODY BGCOLOR="#FFFFFF" TEXT="#000000">



<H2>Chapter 26</H2>

<H2>Exceptions, Templates, and the Latest Additions to C++</H2>

<hr>

<P>C++ is an evolving language, and frequently undergoes review and improvement. New power features that have been added to C++ in the recent past are exceptions, templates, Run-Time Type Information (RTTI), namespace support, and some new keywords and 
data types. While most programmers delay learning these concepts until they have six months to a year of Visual C++ programming experience, you should consider learning it now. These concepts are not much more difficult than the ones covered earlier in 
this book, and can add real power to your programs.</P>

<ul>

<li> <B>How to catch, throw, and define exception objects</B></P>

<P>  Exceptions are a better way of handling runtime errors in your programs than using old-fashioned error-handling techniques.</P>

<li> <B>About function templates</B></P>

<P>  Function templates enable you to create a general blueprint for a function. The compiler can then create different versions of the function for you.</P>

<li> <B>How to create and use class templates</B></P>

<P>  Class templates are similar to function templates, except that they act as a blueprint for classes rather than for functions.</P>

<li> <B>About Run-Time Type Information</B></P>

<P>  Run-Time Type Information (RTTI) adds to C++ the ability to safely downcast polymorphic-object pointers, as well as to get information about objects at runtime.</P>

<li> <B>How to define and use namespaces</B></P>

<P>  Identifier scope can be a hassle when you have to include several external libraries into your project. Namespaces help you avoid identifier-name conflict.</P>

<li> <B>New keywords and data types</B></P>

<P>  The new data type <font color="#008000">boolean</font>, and the new keywords <font color="#008000">mutable</font> and <font color="#008000">explicit</font>, eliminate a number of annoying programming troubles.</P>

</ul>

<H3>Understanding Exceptions</H3>

<P>When you write applications using Visual C++, sooner or later you're going to run into error-handling situations that don&#146;t seem to have a solution. Perhaps you are writing a function that returns a numeric value, and need a way to send back an 
error response. Sometimes you can come up with one special return value, perhaps 0 or -1, that indicates a problem. Other times there doesn&#146;t seem to be a way to signal trouble. Or perhaps you use special return values, but find yourself writing code 
that starts out like this:</P>

<pre><font color="#008000">while (somefunction(x))</font></pre>

<pre><font color="#008000">{</font></pre>

<pre><font color="#008000">    for (int i=0; i&lt;limit; i++)</font></pre>

<pre><font color="#008000">    {</font></pre>

<pre><font color="#008000">        y = someotherfunction(i);</font></pre>

<pre><font color="#008000">    }</font></pre>

<pre><font color="#008000">}</font></pre>

<P>Now you realize that if <font color="#008000">someotherfunction()</font> returns -1, you should not move on to the next i, and you should leave the <font color="#008000">while</font> loop. Your code becomes the following:</P>

<pre><font color="#008000">int timetostop = 0;</font></pre>

<pre><font color="#008000">while (somefunction(x) &amp;&amp; !timetostop)</font></pre>

<pre><font color="#008000">{</font></pre>

<pre><font color="#008000">    for (int i=0; i&lt;limit &amp;&amp; !timetostop; i++)</font></pre>

<pre><font color="#008000">    {</font></pre>

<pre><font color="#008000">        if ( (y = someotherfunction(i)) == -1)</font></pre>

<pre><font color="#008000">            timetostop = 1;</font></pre>

<pre><font color="#008000">    }</font></pre>

<pre><font color="#008000">}</font></pre>

<P>This isn&#146;t bad, though it&#146;s getting hard to read. If there are two or three things that could go wrong, your code gets unmanageably complex.</P>

<P>Exceptions are designed to handle just these sorts of problems. The exception mechanism allows programs to signal each other about serious and unexpected problems. There are three places in your code that participate in most exceptions:</P>

<ul>

<li> The <I>try block</I> marks the code you believe might run into difficulty.</P>

<li> The <I>catch block</I>, immediately following the try block, holds the code that deals with the problem.</P>

<li> The <I>throw statement</I> is how the code with a problem notifies the calling code.</P>

</ul>

<P><B>Simple Exception Handling</B></P>

<P>The mechanism used by exception-handling code is really pretty simple. You place the source code that you want guarded against errors inside a <font color="#008000">try</font> block. You then construct a <font color="#008000">catch</font> program block 
that acts as the error handler. If the code in the <font color="#008000">try</font> block (or any code called from the <font color="#008000">try</font> block) throws an exception, the <font color="#008000">try</font> block immediately ceases execution and 
the program continues inside the <font color="#008000">catch</font> block.</P>

<P>For example, memory allocation is one place in a program where you might expect to run into trouble. Listing 26.1 shows a nonsensical little program that allocates some memory and then immediately deletes it. Because memory allocation could fail, the 
code that allocates the memory is enclosed in a <font color="#008000">try</font> program block. If the pointer returned from the memory allocation is <font color="#008000">NULL</font>, the <font color="#008000">try</font> block throws an exception. In this 
case, the exception object is a string.</P>

<blockquote><p><img src="note.gif" tppabs="http://www.mcp.com/814147200/0-7897/0-7897-1145-1/note.gif">

<P>The sample applications in this chapter are console applications, which can run from a DOS prompt and don&#146;t have a graphical interface. This keeps them small enough to be shown in their entirety in the listings. To try them yourself, create a 
console application as discussed in <A HREF="index28.htm" tppabs="http://www.mcp.com/814147200/0-7897/0-7897-1145-1/index28.htm" target="text">Chapter 28</A>, &#147;Future Explorations,&#148; add a file to the project, and add the code shown here.</P>

<p><img src="bottom.gif" tppabs="http://www.mcp.com/814147200/0-7897/0-7897-1145-1/bottom.gif"></blockquote>

<P><I>Listing 26.1&#151;EXCEPTION1.CPP&#151;Simple Exception Handling</I></P>

<pre><font color="#008000">#include &lt;iostream.h&gt;</font></pre>

<pre><font color="#008000">int main()</font></pre>

<pre><font color="#008000">{</font></pre>

<pre><font color="#008000">    int* buffer;</font></pre>

<pre><font color="#008000">    try</font></pre>

<pre><font color="#008000">    {</font></pre>

<pre><font color="#008000">        buffer = new int[256];</font></pre>

<pre><font color="#008000">        if (buffer == NULL)</font></pre>

<pre><font color="#008000">            throw &quot;Memory allocation failed!&quot;;</font></pre>

<pre><font color="#008000">        else</font></pre>

<pre><font color="#008000">            delete buffer;</font></pre>

<pre><font color="#008000">    }</font></pre>

<pre><font color="#008000">    catch(char* exception)</font></pre>

<pre><font color="#008000">    {</font></pre>

<pre><font color="#008000">        cout &lt;&lt; exception &lt;&lt; endl;</font></pre>

<pre><font color="#008000">    }</font></pre>

<pre><font color="#008000">    return 0;</font></pre>

<pre><font color="#008000">}</font></pre>

<P>When the program throws the exception, program execution jumps to the first line of the <font color="#008000">catch</font> program block. (The remainder of the code inside the try block is not executed.) In the case of Listing 26.1, this line just 
prints out a message, after which the function's <font color="#008000">return</font> line is executed and the program ends.</P>

<P>If the memory allocation is successful, the program executes the entire <font color="#008000">try</font> block, deleting the buffer. Then program execution skips over the <font color="#008000">catch</font> block completely, in this case going directly 
to the <font color="#008000">return</font> statement.</P>

<blockquote><p><img src="note.gif" tppabs="http://www.mcp.com/814147200/0-7897/0-7897-1145-1/note.gif">

<P>The <font color="#008000">catch</font> program block does more than direct program execution. It actually catches the exception object thrown by the program. For example, in Listing 26.1, you can see the exception object being caught inside the 
parentheses following the <font color="#008000">catch</font> keyword. This is very similar to a parameter being received by a method. In this case, the type of the &quot;parameter&quot; is <font color="#008000">char*</font> and the name of the parameter is 
<font color="#008000">exception</font>.</P>

<p><img src="bottom.gif" tppabs="http://www.mcp.com/814147200/0-7897/0-7897-1145-1/bottom.gif"></blockquote>

<P><B>Exception Objects</B></P>

<P>The beauty of C++ exceptions is that the exception object thrown can be just about any kind of data structure you like. For example, you might want to create an exception class for certain kinds of exceptions that occur in your programs. Listing 26.2 
shows a program that defines a general-purpose exception class called <font color="#008000">MyException</font>. In the case of a memory-allocation failure, the main program creates an object of the class and throws it. The <font 
color="#008000">catch</font> block catches the <font color="#008000">MyException</font> object, calls the object's <font color="#008000">GetError()</font> member function to get the object's error string, and then displays the string on the screen.</P>

<P><I>Listing 26.2&#151;EXCEPTION2.CPP&#151;Creating an Exception Class</I></P>

<pre><font color="#008000">#include &lt;iostream.h&gt;</font></pre>

<pre><font color="#008000">class MyException</font></pre>

<pre><font color="#008000">{</font></pre>

<pre><font color="#008000">protected:</font></pre>

<pre><font color="#008000">    char* m_msg;</font></pre>

<pre><font color="#008000">public:</font></pre>

<pre><font color="#008000">    MyException(char *msg) { m_msg = msg; }</font></pre>

<pre><font color="#008000">    ~MyException(){}</font></pre>

<pre><font color="#008000">    char* GetError() {return m_msg; };</font></pre>

<pre><font color="#008000">};</font></pre>

<pre><font color="#008000">int main()</font></pre>

<pre><font color="#008000">{</font></pre>

<pre><font color="#008000">    int* buffer;</font></pre>

<pre><font color="#008000">    </font></pre>

<pre><font color="#008000">    try</font></pre>

<pre><font color="#008000">    {</font></pre>

<pre><font color="#008000">        buffer = new int[256];</font></pre>

<pre><font color="#008000">        if (buffer == NULL)</font></pre>

<pre><font color="#008000">        {</font></pre>

<pre><font color="#008000">            MyException* exception =</font></pre>

<pre><font color="#008000">                new MyException(&quot;Memory allocation failed!&quot;);</font></pre>

<pre><font color="#008000">            throw exception;</font></pre>

<pre><font color="#008000">        }</font></pre>

<pre><font color="#008000">        else</font></pre>

<pre><font color="#008000">            delete buffer;</font></pre>

<pre><font color="#008000">    }</font></pre>

<pre><font color="#008000">    catch(MyException* exception)</font></pre>

<pre><font color="#008000">    {</font></pre>

<pre><font color="#008000">        char* msg = exception-&gt;GetError();</font></pre>

<pre><font color="#008000">        cout &lt;&lt; msg &lt;&lt; endl;</font></pre>

<pre><font color="#008000">    }</font></pre>

<pre><font color="#008000">    return 0;</font></pre>

<pre><font color="#008000">}</font></pre>

<P>An exception object can be as simple as an integer error code or as complex as a fully developed class. MFC provides a number of exception classes, including <font color="#008000">CException</font> and several classes derived from it. The abstract 
class <font color="#008000">CException</font> has a constructor and three member functions: <font color="#008000">Delete()</font>, which deletes the exceptions, <font color="#008000">GetErrorMessage()</font>, which returns a string describing the 
exception, and <font color="#008000">ReportError()</font>, which reports the error in a message box.</P>

<P><B>Placing the </B><B><I>catch</I></B><B> Block</B></P>

<P>The <font color="#008000">catch</font> program block doesn't have to be in the same function as the one in which the exception is thrown. When an exception is thrown, the system starts &quot;unwinding the stack,&quot; looking for the nearest <font 
color="#008000">catch</font> block. If the <font color="#008000">catch</font> block is not found in the function that threw the exception, the system looks in the function that called the throwing function. This search continues on up the function-call 
stack. If the exception is never caught, the program halts.</P>

⌨️ 快捷键说明

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