Blog |

Throwing Exceptions in C++

Throwing Exceptions in C++
Table of Contents

When C++ code is executed, various types of errors can occur in the program - coding errors made by programmers, errors due to incorrect input or other unforeseen errors.

When an error occurs, C++ usually stops the program execution and generates an error message. In most scenarios, the preferred way to report and handle both logic and runtime errors is to use exceptions. Exceptions provide a formal and well-defined way for detecting errors and to pass the information up the call stack.

 

Why Use Exceptions in C++?

Exceptions provide a way to react to exceptional circumstances in programs by transferring control to special functions called handlers.

Throwing exceptions are preferred in modern C++ over traditional error handling for the following reasons:

C++ exceptions force the calling code to identify error conditions and handle them. This prevents them from stopping program execution.

C++ destroys all objects in scope after an exception occurs, thereby reducing resource usage.

An exception provides a clean separation between the code that identifies an error and the code that throws and handles the C++ error.

C++ error types can be grouped together, which allows creating a hierarchy of exception objects, grouping them in namespaces or classes and categorizing them according to type.

 

C++ try catch and throw

Exception handling in C++ is done using three keywords: try, catch and throw.

To catch exceptions, a portion of code is placed under exception inspection. This is done by enclosing this portion of code in a try block. When an exception occurs within the try block, control is transferred to the exception handler. If no exception is thrown, the code continues normally and the handlers are ignored.

An exception in C++ is thrown by using the throw keyword from inside the try block. The throw keyword allows the programmer to define custom exceptions.

Exception handlers in C++ are declared with the catch keyword, which is placed immediately after the try block. Multiple handlers (catch expressions) can be chained - each one with a different exception type. Only the handler whose argument type matches the exception type in the throw statement is executed.

C++ does not require a finally block to make sure resources are released if an exception occurs.

 

C++ Throw Exception Example

The following example shows the syntax for throwing and catching exceptions in C++:

#include <iostream>
#include <stdexcept>

using namespace std;

int AddPositiveIntegers(int a, int b)
{
    if (a < 0 || b < 0)
        throw std::invalid_argument("AddPositiveIntegers arguments must be positive");

    return (a + b);
}

int main()
{
    try
    {
        cout << AddPositiveIntegers(-1, 2); //exception
    }

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

    return 0;
}

In this C++ throw exception example, the AddPositiveIntegers() function is called from inside the try block in the main() function. The AddPositiveIntegers() expects two integers a and b as arguments, and throws an invalid_argument exception in case any of them are negative.

The std::invalid_argument class is defined in the standard library in the <stdexcept> header file. This class defines types of objects to be thrown as exceptions and reports errors in C++ that occur because of illegal argument values.

The catch block in the main() function catches the invalid_argument exception and handles it.

 

Throwing exceptions from C++ constructors

An exception should be thrown from a C++ constructor whenever an object cannot be properly constructed or initialized. Since there is no way to recover from failed object construction, an exception should be thrown in such cases.

Constructors should also throw C++ exceptions to signal any input parameters received outside of allowed values or range of values.

Since C++ constructors do not have a return type, it is not possible to use return codes. Therefore, the best practice is for constructors to throw an exception to signal failure.

The throw statement can be used to throw an C++ exception and exit the constructor code.

 

Track, Analyze and Manage C++ Errors With Rollbar

Rollbar in action

Managing errors and throwing exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing C++ errors easier than ever.

Sign Up Today!

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape