C++ throw Exception

The throw keyword in C++ is used to signal an exception, which can then be caught and handled using try and catch blocks.


Syntax of throw

</>
Copy
throw expression;
ParameterDescription
expressionThe value or object to throw as an exception. This can be of any type, including built-in types or user-defined types.

Exception Flow with throw

When an exception is thrown using the throw keyword, the program looks for a matching catch block to handle the exception. If no matching handler is found, the program terminates by calling std::terminate.


Examples for throw

Example 1: Basic Exception Handling

This example demonstrates throwing and catching a standard exception:

</>
Copy
#include <iostream>
#include <stdexcept>

int main() {
    try {
        throw std::runtime_error("An error occurred!");
    } catch (const std::exception& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }

    return 0;
}

Output:

Caught exception: An error occurred!

Example 2: Throwing Custom Exceptions

This example demonstrates how to define and throw a custom exception class:

</>
Copy
#include <iostream>
#include <string>

class CustomException {
    std::string message;

public:
    explicit CustomException(const std::string& msg) : message(msg) {}

    const char* what() const noexcept {
        return message.c_str();
    }
};

int main() {
    try {
        throw CustomException("Custom exception occurred!");
    } catch (const CustomException& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }

    return 0;
}

Output:

Caught exception: Custom exception occurred!

Best Practices for Using throw

When using throw, consider the following best practices:

  1. Use exceptions for exceptional circumstances, not regular control flow.
  2. Always provide meaningful messages for exceptions.
  3. Prefer throwing standard exceptions (e.g., std::runtime_error) over custom ones when possible.
  4. Ensure proper cleanup using try/catch blocks or RAII (Resource Acquisition Is Initialization).

Exception Safety

Make your code exception-safe by following these principles:

  1. Use std::unique_ptr or std::shared_ptr for managing dynamic memory.
  2. Avoid leaking resources by handling exceptions with destructors or smart pointers.
  3. Write exception-safe functions with no side effects if exceptions occur.