Exception Handling In C++ Explained With Simple Example

Exception Handling in C++ allows a programmer to handle run time errors in an orderly fashion. Using this routine, an error handling function can be invoked which can take some corrective action to avoid system crash or to recover the system from errors.
Exception Handling in C++ is built using three keywords – try, catch and throw.
In general, all the code which might throw some error put into try block and expected errors are caught using catch block.
If an error occurred in try block then that error is thrown (error can be thrown explicitly by calling throw also) which will be caught by relevant catch block.

Exception Handling Syntax

Let’s look into the Exception Handling syntax in C++.

try {
// some code
}
catch (type1 arg) {
// handle exception
}
catch (type2 arg) {
// handle exception
}
.
.
.
catch (typeN arg) {
// handle exception
}

Example

Let’s look into an example to understand exception handling.

int main ()
{
    try
    {
        try
        {
            throw short(10);
        }
        catch (short x)
        {
            std::cout << "Caught exception here in short: " << x << std:: endl;
            throw 100;
        }
        catch (int x)
        {
            std::cout << "Caught exception here in int: " << x << std:: endl;
            throw 5.2;
        }
        catch (...)
        {
            std::cout << "Caught generic exception here: " << std:: endl;
        }
    }
    catch (...)
    {
        std::cout << "Caught generic exception at outside: " << std:: endl;
    }
}

Let’s analyze the output of above main function.

Caught exception here in short: 10
Caught generic exception at outside:

As you can see try/catch block can be nested and catch block is selected based on the exception type.
Also, exception can be thrown from catch block also.

Important Points

  • Exception can be caught only if throws from try/catch block.
  • If there is no proper Catch block for the exception thrown from try block then program will crash.
  • Any number of catch block can be associated with one try block.
  • Exception can be thrown from Catch block also.
  • try/catch block can be nested.
  • try block execution stops when an Exception is occurred and control moves to catch block code.

Exception Handling with Inheritance

In case of exceptions where thrown object is of type base and derived classes, programmer needs to be extra cautious. In order to catch the exception correctly, Catch blocks should be placed in reverse order of inheritance.
Let’s analyze this behavior by looking into an example.

class Base
{
    public:
        int x;
};

class Derived:public Base
{
    public:
        int y;
};

/* Catch block is placed in reverse order of inheritance */
void fun2 ()
{
    try
    {
        throw Derived ();
    }
    catch (Derived d)
    {
        std::cout << "Caught exception here in Derived class block" << std:: endl;
    }
    catch (Base b)
    {
        std::cout << "Caught exception here in Base class block" << std:: endl;
    }
}

/* Catch block is placed in order of inheritance.
 * This function might throw warning in some compilers.
 */
void fun3 ()
{
    try
    {
        throw Derived ();
    }
    catch (Base b)
    {
        std::cout << "Caught exception here in Base class block" << std:: endl;
    }
    catch (Derived d)
    {
        std::cout << "Caught exception here in Derived class block" << std:: endl;
    }
}

Let’s look into an main function which uses above function.

int main ()
{
    fun2 ();
    fun3 ();
}

Let’s analyze the output of above main function.

Caught exception here in Derived class block
Caught exception here in Base class block

As you can see, in first function proper Catch block is executed whereas in second case proper catch block is not executed.
So looking into this example we can state that Catch block is picked via top-down approach and the block which satisfies the exception type will be called to handle the exception.

Catching all exceptions

In C++, there is a way to avoid writing such a long Catch block for each Exception type.
In C++, we can define a Catch block which can catch all type of exceptions.
Let’s look into the syntax of such catch block.

catch (...) {
// Handle exception
}

Controlling Exception thrown from a function

In C++, there is a way to control the exception thrown by the function.
Let’s look into the syntax of restricted exceptions for a function.

<ret-type> <fun-name> (<arg-list>) throw (<exception type list>)
{
// function code.
}

Above function can only throw exception mentioned in the exception list defined after throw keyword.
If the function throws an exception which are not part of defined exception list then that exception will not be caught and program will terminate abruptly.

Leave a Reply

Your email address will not be published. Required fields are marked *