Out of Range Exception in C++
In C++, a runtime error known as a "out of range exception" happens when you try to retrieve an element of a data structure, like an array, vector, or container, using an index or iterator that is outside the valid or allocated range for that data structure. This error is generally thrown when you attempt to read from or write to a memory address that is not part of the data structure. It can lead to undefined behavior and program failure.
- Causes: When items are accessed outside of a data structure's legitimate bounds, out of range exceptions follow. As an example, attempting to retrieve an element at an index that is either larger than or equal to the array's size or the container's total number of items.
- Typical Cases: It is possible to run into out of range exceptions while using standard library containers like as std::vector, std::array, or std::list, or when looping through a collection or accessing components of an array.
- Handling: You should always check the indexes or iterators before accessing elements to avoid out-of-range issues. If statements, try-catch blocks, and the at() function for containers, which has the ability to trigger an exception when an index is out of range, are just a few of the ways that C++ provides for checking limits.
C++ Code:
In C++, you can manage out-of-range exceptions by utilizing the std::out_of_range exception class and methods like try and catch blocks. This C++ code sample shows how to catch and manage an out-of-range exception:
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 7, 9}; try { int value = numbers.at(10); // This will throw an out of range exception } catch (const std::out_of_range& e) { std::cerr << "Out of range exception: " << e.what() << std::endl; } return 0; }
Output:
Out of range exception: vector::_M_range_check: __n (which is 10) >= this->size() (which is 9)
Explanation:
An out-of-range issue occurs when numbers.at(10) in the example above attempt to access an element at index 10, which is outside the numbers vector's valid range (0 to 9).
You must handle these errors appropriately in your code to make sure that your C++ programs are dependable and strong.
Example 2:
#include <iostream> // std::cerr #include <stdexcept> // std::out_of_range #include <vector> // std::vector int main (void) { std::vector<int> myvector(15); try { myvector.at(20)=100; // vector::at throws an out-of-range } catch (const std::out_of_range& oor) { std::cerr << "Out of Range error: " << oor.what() << '\n'; } return 0; }
Output:
Out of Range error: vector::_M_range_check: __n (which is 20) >= this->size() (which is 15)
Example 3:
#include <iostream> #include <string> #include <stdexcept> int main() { std::string text = "Hello, World!"; try { char character = text.at(15); // This will throw an out of range exception std::cout << "Character: " << character << std::endl; // This line will not be executed } catch (const std::out_of_range& e) { std::cerr << "Out of range exception: " << e.what() << std::endl; } return 0; }
Output:
Out of range exception: basic_string::at: __n (which is 15) >= this->size() (which is 13)
Explanation:
- For the std::out_of_range exception class, we include <stdexcept> and <string>, which are the required headers.
- Using the content "Hello, World!", we create a std::string named text.
- The try block uses text.at(15) to try and access a character at index 15 of the text string. An std::out_of_range exception will be raised because this index is out of range (the string's valid indices are 0 to 11).
- Using e.what() to print an error message and offer details about the exception, we catch the std::out_of_range exception in the catch block.
Example 4:
#include <iostream> #include <stdexcept> class MyArray { public: MyArray(int size) : size(size), data(new int[size]) {} int& operator[](int index) { if (index < 0 || index >= size) { throw std::out_of_range("Index out of range"); } return data[index]; } ~MyArray() { delete[] data; } private: int* data; int size; }; int main() { MyArray numbers(10); try { int value = numbers[15]; // This will throw an out of range exception std::cout << "Value: " << value << std::endl; // This line will not be executed } catch (const std::out_of_range& e) { std::cerr << "Out of range exception: " << e.what() << std::endl; } return 0; }
Output:
Out of range exception: Index out of range
Conclusion:
In C++, out-of-range exceptions are an essential component of stable and dependable program development. They appear when an attempt is made to access elements—like arrays, vectors, or containers—that are not permitted within data structures. By offering a means to gracefully resolve failures brought on by index or iterator misuse, these exceptions aid in the prevention of undefined behavior, crashes, and memory corruption. Developers may detect and handle out-of-range conditions in their code, increasing its resilience and usability, by utilizing try-catch blocks and the std::out_of_range exception class. When dealing with arrays, strings, or custom data structures in particular, it is crucial to handle out of range exceptions correctly to preserve code integrity, facilitate debugging, and guarantee seamless program operation.