| by Arround The Web | No comments

C++ Custom Exceptions

Exception in C++ is a core concept. An exception occurs on the execution time when the program encounters runtime inconsistencies or unusual scenarios. In C++, the terms “throw”, “try”, and “catch” are used to handle or catch the exception. The “throw” command is utilized to generate the exception. The “try” term serves to throw the exception, and the “catch” keyword represents handling an exception that is developed with the “throw” term and is thrown by the “try” section.  Let’s dive into some examples to demonstrate the exceptions in C++.

Example 1: Program to Create a Custom Exception Class in C++

This simple example is implemented to demonstrate the custom exception handling and detection in C++.

#include <iostream>
#include <exception>
using namespace std;

class DemoException: public exception
{
    virtual const char* what() const throw()
    {
        return "Caught Custom Exception";
    }
};
int main ()
{
    DemoException dEx;
    try
    {
        throw dEx;
    }
    catch (exception& except)
    {
        cout << except.what() << endl;
    }
    return 0;
}

We define the header file in the code including the “iostream” and “exception”. The “iostream” is specifically called for the input and output stream, whereas the “exception” library is called out to handle the exception. After this, we create the “DemoException” class that is derived from the “exception” class of C++. Here, we set the virtual what() function that is used to provide the const char* which displays the results of an error message that is linked to the exception.

Then, we invoke a main() function where we create the “dEx” object of the “DemoException” class. After that, we have a “try” block definition which throws the exception if encountered. Here, we throw the “dEx” object.

Next, we set the “catch” block to catch the exception and handle it. We pass the reference of the class exception as a parameter to catch the exception that is derived from it. Inside the “catch” block, we call the what() function on “except” to get the exception message on the console.

After executing the given program, the custom exception message is caught and thrown on the console:

Example 2: Program to Create a Custom Exception Using Two Classes

The program emphasizes dealing with multiple exceptions that can be handled independently by defining multiple classes.

#include <iostream>
using namespace std;

class evaluation1{};
class evaluation2{};

int main() {
    try{
        throw evaluation1();
    }
    catch(evaluation1 e) {
        cout << "Evaluation1 exception Caught!" << endl;
    }
    try{
        throw evaluation2();
    }
    catch(evaluation2 e) {
        cout << "Evaluation 2 exception Caught!" << endl;
    }

    return 0;
}

In the given code, we have the definition of two classes, “Evaluation1” and “Evaluation2”, which are now empty. After that, we carry out the program’s main() function. Here, we set the try{} block where the “throw” keyword is used to throw the instance of the “Evaluation1()” class. This represents that the “Evaluation1” exception is thrown if any exception arises in the program inside this “try” block. After that, we have a catch{} block where the exception is caught and displays the message of the exception.

Similarly, we have a definition of another try{} block for the “Evaluation2” class. Inside that try{} block, we throw the instance of the “Evaluation2” class. This throws the exception of “Evaluation2” if an error occurs here. Then, we call the catch{} block to display the exception message using the “cout” command if the exception is caught within this block.

The two exceptions of the different “try-catch” blocks are thrown in the console which are handled by the two different classes.

Example 3: Program to Create a Custom Exception with Constructor

The program uses the constructor for handling the exception. Even though we cannot get the values from the constructor, we can achieve this using the “try-catch” block.

#include <iostream>
using namespace std;

class Test {
    int val;

public:
    Test(int n)
    {
        try {
            if (n == 0)
            val = n;
            display();
        }

        catch (const char* exp) {
            cout << "Exception found \n ";
            cout << exp << endl;
        }

    }

    void display()
    {
        cout << "Value = " << val << endl;
    }
};

int main()
{

    Test(0);
    cout << "Creating instance again \n";
    Test(1);
}

In the given code, we establish the “Test” class where the variable is declared as “val” of type integer.  Then, we have a definition of the “Test()” constructor function which is passed with the “n” variable. We then set the “try-catch” block within the “Test()” constructor function. The try block is called with the if() statement. If the value of “n” equals zero, the “catch” block will catch the exception, and the exception message will be thrown on the prompt. The value of “n” is stored in the “val” variable as we initialize it.

After that, we call the display() function to show the value that is stored in the “val” variable. Next, we have the definition of the “catch” block where the exception that is thrown by the “try” block is handled. Finally, we invoke the main() function. Inside which, we call the “Test()”constructor. The constructor is triggered when the object of the “Test()” class is created and specified with the value of “0” on which the exception is thrown.

After that, we call the “Test()” class again to create an instance that is passed with the value of 1. Here, the constructor will not throw any exception since the value is not equal to 0. The display() function will execute and print the value of  “val”.

The custom exception is thrown on the console by calling the constructor. Also, when the condtion is satisfied, the constructor executes without any exception.

Example 4: Program to Create a User-Defined Custom Exception

The program here handles and catches the exception that is defined by the user when asked in the prompt.

#include <iostream>
#include <exception>
using namespace std;
class MyDemo : public exception{
    public:
        const char * what() const throw()
        {
            return "Exception! Tried dividing by zero.!\n";
        }
    };
int main()
{
    try
    {
        int n1, n2;
        cout << "Enter the two integers : \n";
        cin >> n1 >> n2;
        if (n2 == 0)
        {
            MyDemo n3;
            throw n3;
        }
        else
        {
            cout << "n1 / n2 = " << n1/n2 << endl;
        }
    }
    catch(exception& exc)
    {
        cout << exc.what();
    }
}

In the given code, we first define the “MyDemo()” class which is the dependent class of the exception. After that, we set the public what() function with the “virtual” keyword. The what() function is called out to get the cause of the exception in the program when the throw() function throws the exception. Then, we have a main() function where the try-catch{} blocks are defined to detect and handle the exception. Within the try{} block, we declare two variables, “n1” and “n2”, whose values are taken from the user using the “cin” command. When the values against each “n1” and “n2” variables are received, the “if” condition will check whether the “n2” variable is equal to 0 or not. If so, an exception is thrown or the division results are returned. Lastly, we have a catch{} block which takes the reference of the “exception” class as a parameter inherited from it.

The output shows when the condition is unmet and the program is executed without exception:

Also, we define the value of “0” to the “n2” variable to represent how the exception is thrown and caught in the program.

Conclusion

In conclusion, we demonstrated the important concept of C++ which is an exception. An exception hinders the program’s regular execution. For this, we used the “throw”, “try”, and “catch” keywords to handle the exception that happens in the program. We used these keywords in the previous examples to handle the exception differently.

Share Button

Source: linuxhint.com

Leave a Reply