Use Standard Exception Classes (std::exception)
In this step, you'll learn about standard exception classes in C++ and how to use the std::exception
hierarchy to handle different types of runtime errors. The C++ Standard Library provides a set of predefined exception classes that cover various error scenarios.
Open the WebIDE and create a new file called standard_exceptions.cpp
in the ~/project
directory:
touch ~/project/standard_exceptions.cpp
Add the following code to standard_exceptions.cpp
:
#include <iostream>
#include <stdexcept>
#include <limits>
double divideNumbers(double numerator, double denominator) {
// Check for division by zero using std::runtime_error
if (denominator == 0) {
throw std::runtime_error("Division by zero is not allowed!");
}
return numerator / denominator;
}
void checkArrayIndex(int* arr, int size, int index) {
// Check for out-of-range access using std::out_of_range
if (index < 0 || index >= size) {
throw std::out_of_range("Array index is out of bounds!");
}
std::cout << "Value at index " << index << ": " << arr[index] << std::endl;
}
int main() {
try {
// Demonstrate division by zero exception
std::cout << "Attempting division:" << std::endl;
double result = divideNumbers(10, 0);
}
catch (const std::runtime_error& e) {
std::cout << "Runtime Error: " << e.what() << std::endl;
}
try {
// Demonstrate array index out of range exception
int numbers[] = {1, 2, 3, 4, 5};
int arraySize = 5;
std::cout << "\nAccessing array elements:" << std::endl;
checkArrayIndex(numbers, arraySize, 2); // Valid index
checkArrayIndex(numbers, arraySize, 10); // Invalid index
}
catch (const std::out_of_range& e) {
std::cout << "Out of Range Error: " << e.what() << std::endl;
}
return 0;
}
Let's explore the standard exception classes:
-
std::exception
:
- Base class for all standard exceptions
- Provides a virtual
what()
method to get error description
-
Common derived exception classes:
std::runtime_error
: For runtime errors that can only be detected during program execution
std::out_of_range
: When an index or iterator is out of valid range
- Other common classes include
std::logic_error
, std::invalid_argument
, etc.
Compile and run the program:
g++ standard_exceptions.cpp -o standard_exceptions
./standard_exceptions
Example output:
Attempting division:
Runtime Error: Division by zero is not allowed!
Accessing array elements:
Value at index 2: 3
Out of Range Error: Array index is out of bounds!
Key points about standard exception classes:
- Provide a structured way to handle different types of errors
- Each exception class serves a specific purpose
what()
method returns a descriptive error message
- Helps in creating more robust and informative error handling