stdexcept


Header: <stdexcept>

The <stdexcept> header is part of the C++ Standard Library and defines a set of standard exception classes. These exceptions can be used by both the library itself and C++ programs to report common errors.

Key Characteristics

Exception Classes

Logic Errors (derived from std::logic_error)

  1. std::logic_error: Base class for logic errors
  2. std::domain_error: Domain error exception
  3. std::invalid_argument: Invalid argument exception
  4. std::length_error: Length error exception
  5. std::out_of_range: Out-of-range exception

Runtime Errors (derived from std::runtime_error)

  1. std::runtime_error: Base class for runtime errors
  2. std::range_error: Range error exception
  3. std::overflow_error: Overflow error exception
  4. std::underflow_error: Underflow error exception

Example 1: Handling Invalid Arguments

#include <iostream>
#include <stdexcept>
#include <cmath>

double calculateSquareRoot(double number) {
    if (number < 0) {
        throw std::invalid_argument("Negative input is not allowed");
    }
    return std::sqrt(number);
}

int main() {
    try {
        std::cout << calculateSquareRoot(-9) << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}

Explanation

Example 2: Using Out-of-Range Exception

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

int main() {
    std::vector<int> vec = {1, 2, 3};
    try {
        std::cout << vec.at(5) << std::endl;
    } catch (const std::out_of_range& e) {
        std::cerr << "Out of range error: " << e.what() << std::endl;
    }
    return 0;
}

Explanation

Additional Considerations

Summary

The <stdexcept> header provides a set of standard exception classes that form the foundation of error handling in C++. By using these predefined exceptions, developers can create more consistent and maintainable error-handling code. The header defines exceptions for both logic errors (issues that could be detected at compile time) and runtime errors (issues that can only be detected during program execution). Proper use of these exceptions can lead to more robust and reliable C++ programs.

Citations:

[1] https://cplusplus.com/reference/stdexcept/ [2] https://en.cppreference.com/w/cpp/header/stdexcept [3] https://stdcxx.apache.org/doc/stdlibref/stdexcept-h.html [4] https://www.geeksforgeeks.org/exception-header-in-cpp-with-examples/ [5] https://stdcxx.apache.org/doc/stdlibug/18-4.html [6] https://www.machinet.net/tutorial-eng/common-uses-of-stdexcept-in-modern-cpp-programming [7] https://www.tutorialspoint.com/cpp_standard_library/stdexcept.htm

Previous Page | Course Schedule | Course Content