Utilizar clases de excepciones estándar (std::exception
)
En este paso, aprenderás sobre las clases de excepciones estándar en C++ y cómo utilizar la jerarquía de std::exception
para manejar diferentes tipos de errores en tiempo de ejecución. La Biblioteca Estándar de C++ proporciona un conjunto de clases de excepciones predefinidas que cubren diversos escenarios de error.
Abre el WebIDE y crea un nuevo archivo llamado standard_exceptions.cpp
en el directorio ~/project
:
touch ~/project/standard_exceptions.cpp
Agrega el siguiente código a 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;
}
Exploremos las clases de excepciones estándar:
-
std::exception
:
- Clase base para todas las excepciones estándar
- Proporciona un método virtual
what()
para obtener la descripción del error
-
Clases de excepciones derivadas comunes:
std::runtime_error
: Para errores en tiempo de ejecución que solo se pueden detectar durante la ejecución del programa
std::out_of_range
: Cuando un índice o iterador está fuera del rango válido
- Otras clases comunes incluyen
std::logic_error
, std::invalid_argument
, etc.
Compila y ejecuta el programa:
g++ standard_exceptions.cpp -o standard_exceptions
./standard_exceptions
Ejemplo de salida:
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!
Puntos clave sobre las clases de excepciones estándar:
- Proporcionan una forma estructurada de manejar diferentes tipos de errores
- Cada clase de excepción tiene un propósito específico
- El método
what()
devuelve un mensaje de error descriptivo
- Ayudan a crear un manejo de errores más robusto e informativo