Exceptions Classes And Inheritance
Exceptions and member functions
- Exceptions are useful in member functions.
Example: Overloaded [] operator. However, value nIndex should be a valid array index and this is not checked.
int IntArray::operator[](const int nIndex) { return m_nData[nIndex]; }
With the use of an exception: Now, if the user passes in an invalid exception, operator[] will throw an int exception.
int IntArray::operator[](const int nIndex) { if (nIndex < 0 || nIndex >= GetLength()) throw nIndex; return m_nData[nIndex]; }
Constructors
- When constructors fail, it cannot return a value.
- You could simply throw an exception to indicate the object failed to create.
Exception class
- An exception class is just a normal class that is designed specifically to be thrown as an exception.