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.
<stdexcept>
headerstd::exception
#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;
}
validateAge
that throws a std::runtime_error
for invalid age values.main()
, we use a try-catch block to handle the potential exception.what()
method is used to get the error message.#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;
}
NetworkError
class derived from std::runtime_error
.connectToServer
function demonstrates throwing this custom exception.main()
, we catch NetworkError
specifically to access the error code.#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;
}
DataProcessor
class has a method calculateAverage
that throws a std::runtime_error
if the data set is empty.main()
function.Performance: Throwing and catching exceptions can have performance implications, especially in performance-critical code paths.
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.
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.
noexcept Specifier: If a function is not supposed to throw exceptions, consider marking it with noexcept
.
Error Codes vs Exceptions: In some cases, especially in large-scale or performance-critical applications, error codes might be preferred over exceptions.
std::runtime_error
in C++ is a versatile exception class for handling runtime errors:
std::exception
, it provides a what()
method for error description.<stdexcept>
to use std::runtime_error
.std::exception
.std::runtime_error
.std::out_of_range
, std::invalid_argument
).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.