std::runtime_error


Class: std::runtime_error

std::runtime_error is a standard exception class in C++ that represents errors that can be detected only during program execution. It's part of the <stdexcept> header and is derived from std::exception. This class is typically used for reporting errors that are due to events beyond the scope of the program and can't be easily predicted.

Key Characteristics

Example 1: Basic Usage of std::runtime_error

#include <iostream>
#include <stdexcept>
#include <string>

void validateAge(int age) {
    if (age < 0 || age > 150) {
        throw std::runtime_error("Invalid age value");
    }
    std::cout << "Age is valid: " << age << std::endl;
}

int main() {
    try {
        validateAge(25);  // This should work fine
        validateAge(-5);  // This should throw an exception
    }
    catch (const std::runtime_error& e) {
        std::cerr << "Caught a runtime_error: " << e.what() << std::endl;
    }

    return 0;
}

Explanation:

Example 2: Custom Exception Derived from std::runtime_error

#include <iostream>
#include <stdexcept>
#include <string>

class NetworkError : public std::runtime_error {
public:
    NetworkError(const std::string& message) 
        : std::runtime_error(message), errorCode(0) {}
    NetworkError(const std::string& message, int code) 
        : std::runtime_error(message), errorCode(code) {}

    int getErrorCode() const { return errorCode; }

private:
    int errorCode;
};

void connectToServer(const std::string& server) {
    if (server.empty()) {
        throw NetworkError("Empty server address", 404);
    }
    // Simulating a connection error
    throw NetworkError("Failed to connect to server: " + server, 500);
}

int main() {
    try {
        connectToServer("example.com");
    }
    catch (const NetworkError& e) {
        std::cerr << "Network error: " << e.what() 
                  << " (Error code: " << e.getErrorCode() << ")" << std::endl;
    }
    catch (const std::exception& e) {
        std::cerr << "Standard exception: " << e.what() << std::endl;
    }

    return 0;
}

Explanation:

Example 3: Using std::runtime_error in a Class Method

#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

class DataProcessor {
private:
    std::vector<int> data;

public:
    void addData(int value) {
        data.push_back(value);
    }

    double calculateAverage() const {
        if (data.empty()) {
            throw std::runtime_error("Cannot calculate average of empty dataset");
        }

        double sum = 0;
        for (int value : data) {
            sum += value;
        }
        return sum / data.size();
    }
};

int main() {
    DataProcessor processor;

    try {
        std::cout << "Average: " << processor.calculateAverage() << std::endl;
    }
    catch (const std::runtime_error& e) {
        std::cerr << "Runtime error caught: " << e.what() << std::endl;
    }

    processor.addData(10);
    processor.addData(20);
    processor.addData(30);

    try {
        std::cout << "Average: " << processor.calculateAverage() << std::endl;
    }
    catch (const std::runtime_error& e) {
        std::cerr << "Runtime error caught: " << e.what() << std::endl;
    }

    return 0;
}

Explanation:

Additional Considerations

  1. Performance: Throwing and catching exceptions can have performance implications, especially in performance-critical code paths.

  2. Exception Safety: Ensure that your code is exception-safe, meaning it doesn't leak resources or leave objects in an inconsistent state when an exception is thrown.

  3. Inheritance Hierarchy: std::runtime_error is part of a hierarchy of standard exceptions. Consider using more specific exceptions (like std::out_of_range) when appropriate.

  4. noexcept Specifier: If a function is not supposed to throw exceptions, consider marking it with noexcept.

  5. Error Codes vs Exceptions: In some cases, especially in large-scale or performance-critical applications, error codes might be preferred over exceptions.

Summary

std::runtime_error in C++ is a versatile exception class for handling runtime errors:

  1. It's used for errors that can only be detected during program execution.
  2. Derived from std::exception, it provides a what() method for error description.
  3. Can be used as a base class for more specific custom exception types.
  4. Typically thrown and caught using standard C++ exception handling mechanisms.

Key points to remember:

Best practices:

std::runtime_error is a powerful tool in C++ for handling unexpected runtime conditions, allowing for robust error handling and improving the overall reliability of your programs.

Related

Previous Page | Course Schedule | Course Content