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

📄 ch20.htm

📁 Why C++ is the emerging standard in software development. The steps to develop a C++ program. How
💻 HTM
📖 第 1 页 / 共 4 页
字号:
97:           cout &lt;&lt; &quot; of zero objects!\n&quot;; 98:        }99:    100:        catch (Array::xTooSmall)101:        {102:           cout &lt;&lt; &quot;This array is too small...\n&quot;;103:        }104: 105:        catch (...)106:        {107:           cout &lt;&lt; &quot;Something went wrong!\n&quot;;108:         }109:          cout &lt;&lt; &quot;Done.\n&quot;;110:        return 0<TT>111: }</TT>Output: This array is too small...Done.</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The significant change ison lines 26-29, where the class hierarchy is established. Classes <TT>xTooBig</TT>,<TT>xTooSmall</TT>, and <TT>xNegative</TT> are derived from <TT>xSize</TT>, and <TT>xZero</TT>is derived from <TT>xTooSmall</TT>.<BR><BR>The <TT>Array</TT> is created with size zero, but what's this? The wrong exceptionappears to be caught! Examine the <TT>catch</TT> block carefully, however, and youwill find that it looks for an exception of type <TT>xTooSmall</TT> before it looksfor an exception of type <TT>xZero</TT>. Because an <TT>xZero</TT> object is thrownand an <TT>xZero</TT> object is an <TT>xTooSmall</TT> object, it is caught by thehandler for <TT>xTooSmall</TT>. Once handled, the exception is not passed on to theother handlers, so the handler for <TT>xZero</TT> is never called.</P><P>The solution to this problem is to carefully order the handlers so that the mostspecific handlers come first and the less specific handlers come later. In this particularexample, switching the placement of the two handlers <TT>xZero</TT> and <TT>xTooSmall</TT>will fix the problem.<H3 ALIGN="CENTER"><A NAME="Heading18"></A><FONT COLOR="#000077">Data in Exceptionsand Naming Exception Objects</FONT></H3><P>Often you will want to know more than just what type of exception was thrown soyou can respond properly to the error. Exception classes are like any other class.You are free to provide data, initialize that data in the constructor, and read thatdata at any time. Listing 20.4 illustrates how to do this.</P><P><A NAME="Heading19"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 20.4. Gettingdata out of an exception object.</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; }19:    20:         // friend function21:        friend ostream&amp; operator&lt;&lt; (ostream&amp;, const Array&amp;);22:    23:       // define the exception classes24:         class xBoundary {};25:         class xSize26:         {27:         public:28:            xSize(int size):itsSize(size) {}29:            ~xSize(){}30:            int GetSize() { return itsSize; }31:         private:32:            int itsSize;33:         };34:    35:         class xTooBig : public xSize36:         {37:         public:38:            xTooBig(int size):xSize(size){}39:         };40:    41:         class xTooSmall : public xSize42:         {43:         public:44:            xTooSmall(int size):xSize(size){}45:         };46:    47:         class xZero  : public xTooSmall48:         {49:         public:50:            xZero(int size):xTooSmall(size){}51:         };52:    53:         class xNegative : public xSize54:         {55:         public:56:            xNegative(int size):xSize(size){}57:         };58:    59:      private:60:         int *pType;61:         int  itsSize;62:      };63:    64: 65:      Array::Array(int size):66:      itsSize(size)67:      {68:         if (size == 0)69:            throw xZero(size);70:         if (size &gt; 30000)71:            throw xTooBig(size);72:         if (size &lt;1)73:            throw xNegative(size);74:         if (size &lt; 10)75:            throw xTooSmall(size);76:    77:         pType = new int[size];78:         for (int i = 0; i&lt;size; i++)79:           pType[i] = 0;80:      }81:    82:    83:      int&amp; Array::operator[] (int offSet)84:      {85:          int size = GetitsSize();86:          if (offSet &gt;= 0 &amp;&amp; offSet &lt; GetitsSize())87:            return pType[offSet];88:          throw xBoundary();89:          return pType[0];90:      }91:    92:      const int&amp; Array::operator[] (int offSet) const93:      {94:          int size = GetitsSize();95:          if (offSet &gt;= 0 &amp;&amp; offSet &lt; GetitsSize())96:            return pType[offSet];97:          throw xBoundary();98:          return pType[0];99:      }100:    101:       int main()102:       {103:    104:          try105:          {106:             Array intArray(9);107:             for (int j = 0; j&lt; 100; j++)108:             {109:                intArray[j] = j;110:                cout &lt;&lt; &quot;intArray[&quot; &lt;&lt; j &lt;&lt; &quot;] okay...&quot; &lt;&lt; endl;111:             }112:          }113:          catch (Array::xBoundary)114:          {115:             cout &lt;&lt; &quot;Unable to process your input!\n&quot;;116:          }117:         catch (Array::xZero theException)118:         {119:            cout &lt;&lt; &quot;You asked for an Array of zero objects!&quot; &lt;&lt; endl;120:            cout &lt;&lt; &quot;Received &quot; &lt;&lt; theException.GetSize() &lt;&lt; endl;121:         }122:         catch (Array::xTooBig theException)123:         {124:            cout &lt;&lt; &quot;This Array is too big...&quot; &lt;&lt; endl;125:            cout &lt;&lt; &quot;Received &quot; &lt;&lt; theException.GetSize() &lt;&lt; endl;126:         }127:         catch (Array::xTooSmall theException)128:         {129:            cout &lt;&lt; &quot;This Array is too small...&quot; &lt;&lt; endl;130:            cout &lt;&lt; &quot;Received &quot; &lt;&lt; theException.GetSize() &lt;&lt; endl;131:         }132:         catch (...)133:         {134:            cout &lt;&lt; &quot;Something went wrong, but I've no idea what!\n&quot;;135:         }136:         cout &lt;&lt; &quot;Done.\n&quot;;137:        return 0;<TT>138: }</TT></FONT><FONT COLOR="#0066FF">Output: This array is too small...Received 9Done.</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The declaration of <TT>xSize</TT>has been modified to include a member variable, <TT>itsSize</TT>, on line 32 anda member function, <TT>GetSize()</TT>, on line 30. Additionally, a constructor hasbeen added that takes an integer and initializes the member variable, as shown online 28.<BR>The derived classes declare a constructor that does nothing but initialize the baseclass. No other functions were declared, in part to save space in the listing.</P><P>The <TT>catch</TT> statements on lines 113 to 135 are modified to name the exceptionthey catch, <TT>theException</TT>, and to use this object to access the data storedin <TT>itsSize</TT>.<BLOCKQUOTE>	<P><HR><FONT COLOR="#000077"><B>NOTE: </B></FONT>Keep in mind that if you are constructing	an exception, it is because an exception has been raised: Something has gone wrong,	and your exception should be careful not to kick off the same problem. Therefore,	if you are creating an <TT>OutOfMemory</TT> exception, you probably don't want to	allocate memory in its constructor. <HR></BLOCKQUOTE><P>It is tedious and error-prone to have each of these <TT>catch</TT> statementsindividually print the appropriate message. This job belongs to the object, whichknows what type of object it is and what value it received. Listing 20.5 takes amore object-oriented approach to this problem, using virtual functions so that eachexception &quot;does the right thing.&quot;</P><P><A NAME="Heading21"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 20.5.Passingby reference and using virtual functions in exceptions.</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; }19:    20:         // friend function21:        friend ostream&amp; operator&lt;&lt; 22:            (ostream&amp;, const Array&amp;);23:    24:       // define the exception classes25:         class xBoundary {};26:         class xSize27:         {28:         public:29:            xSize(int size):itsSize(size) {}30:            ~xSize(){}31:            virtual int GetSize() { return itsSize; }32:            virtual void PrintError() 33:            { 34:                cout &lt;&lt; &quot;Size error. Received: &quot;;35:                cout &lt;&lt; itsSize &lt;&lt; endl; 36:            }37:         protected:38:            int itsSize;39:         };40:    41:         class xTooBig : public xSize42:         {43:         public:44:            xTooBig(int size):xSize(size){}45:            virtual void PrintError() 46:            { 47:                cout &lt;&lt; &quot;Too big! Received: &quot;;48:                cout &lt;&lt; xSize::itsSize &lt;&lt; endl; 49:            }50:         };51:    52:         class xTooSmall : public xSize53:         {54:         public:55:            xTooSmall(int size):xSize(size){}56:            virtual void PrintError() 57:            { 58:                cout &lt;&lt; &quot;Too small! Received: &quot;;59:                cout &lt;&lt; xSize::itsSize &lt;&lt; endl; 60:            }61:         };62: 63:         class xZero  : public xTooSmall64:         {65:         public:66:            xZero(int size):xTooSmall(size){}67:            virtual void PrintError() 68:            { 69:                cout &lt;&lt; &quot;Zero!!. Received: &quot; ;70:                cout &lt;&lt; xSize::itsSize &lt;&lt; endl; 71:            }72:         };73:    74:         class xNegative : public xSize75:         {76:         public:77:            xNegative(int size):xSize(size){}78:            virtual void PrintError() 79:            { 80:                cout &lt;&lt; &quot;Negative! Received: &quot;;81:                cout &lt;&lt; xSize::itsSize &lt;&lt; endl; 82:            }83:         };84:    85:      private:86:         int *pType;87:         int  itsSize;88:      };89:    90:      Array::Array(int size):91:      itsSize(size)92:      {93:         if (size == 0)94:            throw xZero(size);95:         if (size &gt; 30000)96:            throw xTooBig(size);97:         if (size &lt;1)98:            throw xNegative(size);99:         if (size &lt; 10)100:            throw xTooSmall(size);101:    102:         pType = new int[size];103:         for (int i = 0; i&lt;size; i++)104:           pType[i] = 0;105:      }106:    107:      int&amp; Array::operator[] (int offSet)108:      {109:          int size = GetitsSize();110:          if (offSet &gt;= 0 &amp;&amp; offSet &lt; GetitsSize())111:            return pType[offSet];112:          throw xBoundary();113:          return pType[0];114:      }115:    116:      const int&amp; Array::operator[] (int offSet) const117:      {118:          int size = GetitsSize();119:          if (offSet &gt;= 0 &amp;&amp; offSet &lt; GetitsSize())120:            return pType[offSet];121:          throw xBoundary();122:          return pType[0];123:      }124:    125:       int main()126:       {127: 128:          try129:          {130:             Array intArray(9);131:             for (int j = 0; j&lt; 100; j++)132:             {133:                intArray[j] = j;134:                cout &lt;&lt; &quot;intArray[&quot; &lt;&lt; j &lt;&lt; &quot;] okay...\n&quot;;135:             }136:          }137:          catch (Array::xBoundary)138:         {139:            cout &lt;&lt; &quot;Unable to process your input!\n&quot;;140:         }141:         catch (Array::xSize&amp; theException)142:         {143:            theException.PrintError();144:         }145:         catch (...)146:         {147:            cout &lt;&lt; &quot;Something went wrong!\n&quot;;148:         }149:         cout &lt;&lt; &quot;Done.\n&quot;;

⌨️ 快捷键说明

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