C++

How to Throw a C++ Exception

Throwing a C++ exception is an important technique that helps improve the overall structure and stability of code. C++ exceptions are simple objects used to indicate an error condition occurred beyond the scope of what can be handled by normal execution.

This article will provide a detail on how to throw a C++ exception, with a focus on the standard library’s <stdexcept> library and the usage of basic try/catch blocks.

How to Throw a C++ Exception

Before one can begin to learn how to throw a C++ exception, it is important to understand what an exception is. An object used to signify an incorrect state is the exception. The C++ users use it when something unexpected or beyond the capabilities of the program occurs. There are a few different ways to define when and how an exception should be thrown. In general, you can use when an action is taking place that can be considered an abnormal situation. One thing to remember is that when an exception is thrown, it should never be used to indicate an intentional action by the user.

You can transfer control between parts of a program by using exceptions. Try, Catch, and Throw are the three base keywords for C++’s exception handling. When an issue arises, a program will throw an exception using the throw keyword. An exception handler is used by a software to catch an exception at the location where the issue should be handled. The term catch denotes capturing an exception. A try block specifies a section of code that will trigger certain exceptions. A catch block or blocks are then added after it.

By inheriting from and modifying the functionality of exception class, you may create your own exceptions. The example that follows demonstrates how to build your own exception using the std::exception class in a standard manner.

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

struct MyException : public exception {
   const char * what () const throw () {
      return "A C++ Exception";
   }
};

int main() {
   try {
      throw MyException();
   } catch(MyException& e) {
      std::cout << "My exception caught" << std::endl;
      std::cout << e.what() << std::endl;
   } catch(std::exception& e) {
   }
}

In the above example, what() is a public method supplied by the exception class in this case, and all of the child exception classes have overridden it. This provides the exception’s root cause.

Output

An exception ought to be thrown inside a C++ constructor when object building fails, as there is no means to recover. Constructors must additionally throw C++ exceptions to indicate any input parameters that are beyond the range or with values that are not permitted. Return codes cannot be used in C++ constructors because they lack a return type. Therefore, it is recommended that constructors throw exceptions to indicate failure.

To throw a C++ exception and end the constructor code, use the throw statement.

#include <iostream>
#include <stdexcept>

using namespace std;

int AddPositiveInt(int x, int y)
{
    if (x<0 || y<0)
        throw std::invalid_argument("Arguments should be positive");
    return (x + y);
}

int main()
{
    try
    {cout << AddPositiveInt(-1, 2);}

    catch (std::invalid_argument& e)
    {   cerr << e.what() << endl;
        return -1;}

    return 0;
}

In this C++ throw exception example, the AddPositiveInt() method is used from within the try block of the main() function. An invalid argument exception is thrown by the AddPositiveInt() function if any of the two expected parameters, integers x and y, are negative. The standard library’s <stdexcept> header file contains the definition of the std::invalid argument class. This class specifies the sorts of objects that can be thrown as exceptions and logs C++ problems brought on by invalid parameter values. The main() function’s catch block captures and deals with the invalid argument exception.

Output

When to Throw a C++ Exception

Knowing when to throw an exception is the first step, but how do you implement it? The standard library includes a range of classes under the <stdexcept> library, which are often used to throw exceptions. They contain some important information to inform the user about any kind of errors that occur, such as the error message and error type. Once the users identify the appropriate class, they can then use the “throw” keyword to throw the exception.

Conclusion

Throwing a C++ exception is a simple process that handles any kind of errors occurred in the program. It is important to use the <stdexcept> library when throwing exceptions and to use the “try/catch” block structure to find and handle them appropriately. You can be confident that your code can handle errors politely if you do this.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.