C++ throw Keyword

The throw keyword in C++ is used for exception handling. It signals that an error or an unexpected condition has occurred, transferring control from the point of the exception to a catch block where the exception is handled.

The throw statement is typically used in conjunction with try and catch blocks to provide a structured way to handle runtime errors, making programs more robust and reliable.


Syntax

</>
Copy
throw expression;
expression
The exception to be thrown. It can be a literal, variable, or object.
  • The throw statement transfers control to the nearest enclosing catch block that matches the exception type.
  • If no matching catch block is found, the program terminates with an unhandled exception.
  • Exceptions can be any type, but typically std::exception or its derivatives are used for standard error reporting.

Examples

Example 1: Basic Exception Handling

In this example, you will learn how to use throw with a trycatch block to handle a runtime error.

</>
Copy
#include <iostream>
using namespace std;

int divide(int a, int b) {
    if (b == 0) {
        throw "Division by zero error"; // Throw a string exception
    }
    return a / b;
}

int main() {
    try {
        cout << "Result: " << divide(10, 0) << endl;
    } catch (const char* e) {
        cout << "Caught exception: " << e << endl;
    }
    return 0;
}

Output:

Result: Caught exception: Division by zero error

Explanation:

  1. The divide function checks if the divisor is zero and throws an exception if it is.
  2. The try block calls divide, and the throw transfers control to the catch block.
  3. The catch block matches the thrown exception type (const char*) and handles the error by printing a message.

Example 2: Throwing and Catching Objects

This example demonstrates how to throw and catch a user-defined exception class.

</>
Copy
#include <iostream>
#include <string>
using namespace std;

class DivisionError {
public:
    string message;
    DivisionError(string msg) : message(msg) {}
};

int divide(int a, int b) {
    if (b == 0) {
        throw DivisionError("Division by zero is not allowed");
    }
    return a / b;
}

int main() {
    try {
        cout << "Result: " << divide(10, 0) << endl;
    } catch (const DivisionError& e) {
        cout << "Caught exception: " << e.message << endl;
    }
    return 0;
}

Output:

Result: Caught exception: Division by zero is not allowed

Explanation:

  1. The DivisionError class represents a custom exception with a message.
  2. The divide function throws an instance of DivisionError if the divisor is zero.
  3. The catch block matches exceptions of type DivisionError and handles the error by accessing the exception’s message member.

Example 3: Rethrowing Exceptions

This example demonstrates how to rethrow an exception from a catch block.

</>
Copy
#include <iostream>
using namespace std;

void process() {
    try {
        throw "An error occurred"; // Throw a string exception
    } catch (...) {
        cout << "Exception caught in process()" << endl;
        throw; // Rethrow the exception
    }
}

int main() {
    try {
        process();
    } catch (const char* e) {
        cout << "Exception re-caught in main(): " << e << endl;
    }
    return 0;
}

Output:

Exception caught in process()
Exception re-caught in main(): An error occurred

Explanation:

  1. The process function throws an exception and catches it using a catch-all handler (catch (...)).
  2. The catch block in process rethrows the exception using a bare throw.
  3. The rethrown exception is caught again in the main function.

Key Points to Remember about throw Keyword

  • The throw keyword is used to signal an error or exception.
  • Thrown exceptions must be caught by a corresponding catch block.
  • Exceptions can be of any type, including primitive types, classes, or objects.
  • Rethrowing an exception allows further handling in a different context.
  • Unhandled exceptions cause the program to terminate.