Search

15.5 — Exceptions, classes, and inheritance

Exceptions and member functions

Up to this point in the tutorial, you’ve only seen exceptions used in non-member functions. However, exceptions are equally useful in member functions, and even moreso in overloaded operators. Consider the following overloaded [] operator as part of a simple integer array class:

Although this function will work great as long as nIndex is a valid array index, this function is sorely lacking in some good error checking. We could add an assert statement to ensure the index is valid:

Now if the user passes in an invalid index, the program will cause an assertion error. While this is useful to indicate to the user that something went wrong, sometimes the better course of action is to fail silently and let the caller know something went wrong so they can deal with it as appropriate.

Unfortunately, because overloaded operators have specific requirements as to the number and type of parameter(s) they can take and return, there is no flexibility for passing back error codes or boolean values to the caller. However, since exceptions do not change the signature of a function, they can be put to great use here. Here’s an example:

Now, if the user passes in an invalid exception, operator[] will throw an int exception.

When constructors fail

Constructors are another area of classes in which exceptions can be very useful. If a constructor fails, simply throw an exception to indicate the object failed to create. The object’s construction is aborted and its destructor is never executed.

Exception classes

One of the major problems with using basic data types (such as int) as exception types is that they are inherently vague. An even bigger problem is disambiguation of what an exception means when there are multiple statements or function calls within a try block.

In this example, if we were to catch an int exception, what does that really tell us? Was one of the array indexes out of bounds? Did operator+ cause integer overflow? Did operator new fail because it ran out of memory? Unfortunately, in this case, there’s just no easy way to disambiguate. While we can throw char* exceptions to solve the problem of identifying WHAT went wrong, this still does not provide us the ability to handle exceptions from various sources differently.

One way to solve this problem is to use exception classes. An exception class is just a normal class that is designed specifically to be thrown as an exception. Let’s design a simple exception class to be used with our IntArray class:

Here’s our overloaded operator[] throwing this class:

And a sample usage of this class:

Using such a class, we can have the exception return a description of the problem that occurred, which provides context for what went wrong. And since ArrayException is it’s own unique type, we can specifically catch exceptions thrown by the array class and treat them differently from other exceptions if we wish.

Note that exception handlers should catch class exception objects by reference instead of by value. This prevents the compiler from make a copy of the exception, which can be expensive when the exception is a class object. Catching exceptions by pointer should generally be avoided unless you have a specific reason to do so.

std::exception

The C++ standard library comes with an exception class that is used by many of the other standard library classes. The class is almost identical to the ArrayException class above, except the GetError() function is named what():

We’ll talk more about std::exception in a moment.

Exceptions and inheritance

Since it’s possible to throw classes as exceptions, and classes can be derived from other classes, we need to consider what happens when we use inherited classes as exceptions. As it turns out, exception handlers will not only match classes of a specific type, they’ll also match classes derived from that specific type as well! Consider the following example:

In the above example we throw an exception of type Derived. However, the output of this program is:

caught Base

What happened?

First, as mentioned above, derived classes will be caught by handlers for the base type. Because Derived is derived from Base, Derived is-a Base (they have an is-a relationship). Second, when C++ is attempting to find a handler for a raised exception, it does so sequentially. Consequently, the first thing C++ does is check whether the exception handler for Base matches the Derived exception. Because Derived is-a Base, the answer is yes, and it executes the catch block for type Base! The catch block for Derived is never even tested in this case.

In order to make this example work as expected, we need to flip the order of the catch blocks:

This way, the Derived handler will get first shot at catching objects of type Derived (before the handler for Base can). Objects of type Base will not match the Derived handler (Derived is-a Base, but Base is not a Derived), and thus will “fall through” to the Base handler.

Rule: Handlers for derived exception classes should be listed before those for base classes.

The ability to use a handler to catch exceptions of derived types using a handler for the base class turns out to be exceedingly useful.

Let’s take a look at this using std::exception. There are many classes derived from std::exception, such as std::bad_alloc, std::bad_cast, std::runtime_error, and others. When the standard library has an error, it can throw a derived exception correlating to the appropriate specific problem it has encountered.

Most of the time, we probably won’t care whether the problem was a bad allocation, a bad cast, or something else. We just care that we got an exception from the standard library. In this case, we just set up an exception handler to catch std::exception, and we’ll end up catching std::exception and all of the derived exceptions together in one place. Easy!

However, sometimes we’ll want to handle a specific type of exception differently. In this case, we can add a handler for that specific type, and let all the others “fall through” to the base handler. Consider:

In this example, exceptions of type std::bad_alloc will be caught by the first handler and handled there. Exceptions of type std::exception and all of the other derived classes will be caught by the second handler.

Such inheritance hierarchies allow us to use specific handlers to target specific derived exception classes, or to use base class handlers to catch the whole hierarchy of exceptions. This allows us a fine degree of control over what kind of exceptions we want to handle while ensuring we don’t have to do too much work to catch “everything else” in a hierarchy.

15.6 -- Exception dangers and downsides
Index
15.4 -- Uncaught exceptions, catch-all handlers, and exception specifiers

25 comments to 15.5 — Exceptions, classes, and inheritance

  • dear reader

    it should be “making” instead of “make” in:
    “prevents the compiler from make a copy of the exception”.

  • goodsir

    also, i would change “exception”(the first one) to “index” in this line:

    Now, if the user passes in an invalid exception, operator[] will throw an int exception.

  • saurabh

    I think you are missing one topic where programmer can override standard what() function of exception class to redefine their own exception handling . Like example below:

    class myexc : public exception
    {
    virtual const char * what () const throw ()
    {
    return “my own exception”;
    }
    } mye;

    int main()
    {
    try
    {

    throw mye;
    }

    catch (exception & e)
    {
    cout<<e.what()<<"in main cacth ";
    }
    return 0;
    }
    other things i want to hilight that by default a function can throw all type of exception but if we want a function to not throw exception then add throw() at end of function signature like

    myfun() throw()

    Please add a article for this topic.

  • saurabh

    Oops i forget to paste header file part . You need to add following pre directives
    #include
    #include
    using namespace std;

  • DOBRESCU Mihai

    Hi,

    Maybe the reader would be happier if he got the full listing for the first sample program.

    This is the “IntArray.h” header file:


    #ifndef INTARRAY_H
    #define INTARRAY_H

    #include <assert.h> // for assert()

    class ArrayException
    {
    private:
    std::string m_strError;

    ArrayException() {}; // not meant to be called
    public:
    ArrayException(std::string strError)
    : m_strError(strError)
    {
    }

    std::string GetError() { return m_strError; }
    };

    class IntArray
    {
    private:
    int m_nLength;
    int *m_pnData;

    public:
    IntArray()
    {
    m_nLength = 0;
    m_pnData = 0;
    }

    IntArray(int nLength)
    {
    m_pnData = new int[nLength];
    m_nLength = nLength;
    }

    ~IntArray()
    {
    delete[] m_pnData;
    }

    void Erase()
    {
    delete[] m_pnData;
    // We need to make sure we set m_pnData to 0 here, otherwise it will
    // be left pointing at deallocated memory!
    m_pnData = 0;
    m_nLength = 0;
    }

    int& operator[](const int nIndex)
    {
    if (nIndex < 0 || nIndex >= GetLength())
    throw ArrayException("Invalid index");

    return m_pnData[nIndex];
    }

    int GetLength() { return m_nLength; }
    };

    #endif

    This is the “main.cpp” source file:


    #include <iostream>
    #include "IntArray.h"

    using namespace std;

    int main()
    {

    IntArray anArray(3);

    try
    {
    int nValue = anArray[5];
    nValue++;
    }
    catch (ArrayException &cException)
    {
    cerr << "An array exception occurred (" << cException.GetError() << ")" << endl;
    }

    return 0;
    }

    This is the output:


    An array exception occurred (Invalid index)

  • tata

    Since the object below is anonymous,

    why shouldn’t the code below fail, due to the anonymous object being out of its expression scope

    Should the following code be used instead?

    • Alex

      The rule for exceptions is “throw by value, catch by (const) reference”. The compiler deals with the lifetime of the exception appropriately (generally by making a copy of the exception so that the reference points to the persisted copy instead of the anonymous object).

      • tata

        Hi, could I check by understanding by repeating/rephrasing the explanation as:

        ArrayException("Invalide index") is indeed a temporary/anonymous object, which counts as a R-value that cannot be referenced by non-const references; moreover, we have the additional problem that this object will be out of scope before reaching the catch block

        The try/catch mechanism circumvents these problems by making a copy of the anonymous/temporary object and passing instead this copy to the catch block

        Most importantly, since the copy is a L-value, one can reference it using non-const references; moreover, the copy is in scope for the catch block

  • Naga Pushkal

    Hi Alex,

    If an exception is occurred in a constructor, How could we handle them? Can you please elaborate your statement in "When constructors fail" section in this chapter with small example if possible?

    Today I was asked below question in an interview:

    There is a "class A". And "class B" is derived from "class A". An exception is occurred in class A’s constructor. So how would "class B" knows about this exception?

    BTW, Merry Christmas 🙂

    • Alex

      Great question! I think for this, the only solution would be to use a function level try block. See http://en.cppreference.com/w/cpp/language/function-try-block for details.

      Here’s a sample I wrote:

      This prints:

      exception caught in Derived
      exception caught in main
      
  • Inc

    Consider giving a short explanation about function-try-blocks http://en.cppreference.com/w/cpp/language/function-try-block

  • Lokesh

    #typo
    Section "Exception classes", 2nd example, line 6: no semicolon needed

  • Alexander Bieniek

    Do exception handlers treat enumerated types as integers? If not, would they be a similar way to find another type of object to throw?

    Also, are similar data types treated the same way? Would a catch block catch a float if the block was looking for a double?

    • Alex

      You can throw and catch enums:

      A catch block for a double won’t catch a float, nor would a catch block for an integer catch a char or a short.

  • SJ

    Hi Alex,

    I believe the return value for the operator[] overloads should be reference to int, i.e. changing

    to

  • SJ

    I am a bit confused with regards to exception classes. In the example,

    what exactly does the line

    do? I believe it is a constructor, but why is it included under the private access specifier? What purpose does it serve?

  • Ola Sh

    Hello Alex,

    Thanks again for the good tutorial. I followed your example code below; both the catch handlers in main and Derived were executed by the program. Why does the catch handler in main execute if the catch handler in Derived has already handled the exception? Thanks for your help.

    This prints:

    exception caught in Derived
    exception caught in main

    • Alex

      Function try blocks can not absorb an exception and pretend nothing went wrong. They must either throw an exception of their own, or rethrow the same exception.

      So in the case above, the Derived() catch block is rethrowing the exception so that main() can properly handle the object that failed to construct.

  • Matt

    Catch this… Under "Exception classes", in the first sentence, "problem" should be plural:)

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter