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.
std::exception
std::logic_error
)std::logic_error
: Base class for logic errorsstd::domain_error
: Domain error exceptionstd::invalid_argument
: Invalid argument exceptionstd::length_error
: Length error exceptionstd::out_of_range
: Out-of-range exceptionstd::runtime_error
)std::runtime_error
: Base class for runtime errorsstd::range_error
: Range error exceptionstd::overflow_error
: Overflow error exceptionstd::underflow_error
: Underflow error exception#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;
}
std::invalid_argument
for input validation#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;
}
std::out_of_range
is used in the Standard Library (vector::at)noexcept
specifier for functions that don't throw exceptionsThe <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.
[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