An exception is a type of runtime error that disrupts the normal flow of instructions within a program. It is an unexpected event that is not foreseen to occur during the standard execution of the program.
One typical situation leading to an out-of-range exception is attempting to access elements within an array or container using an index that falls below zero or exceeds the data structure's size. Within C++, we have the ability to generate exceptions through the throw keyword and manage them through the try-catch constructs.
The try-catch block is fundamental in handling exceptions. Any section of code that may generate an exception is enclosed within a try-catch block.
When an error is identified by the C++ compiler in the program, the try keyword is employed to trigger the throwing of an exception. The try keyword specifies the segment of the code where the specific issue arose, whereas the catch keyword is responsible for capturing these exceptions.
Programs may encounter the "Out of range" exception, a frequently encountered issue. Within the standard library, exceptions could also be thrown by the vector, deque, string, and bitset components if they stray beyond their designated range.
If a method is given a value that is not within the specified range of expected values, it triggers an exception referred to as "out of range." This exception assists in understanding the cause of errors in the code.
An "out of range" exception in C++ is raised when an attempt is made to access an element outside the permitted range or bounds of a data structure, such as an array, vector, string, or other container. The C++ Standard Library's std::outofrange exception class is commonly used to represent this type of exception. The following is the theory behind the C++ out-of-range exception:
- std::out of range Exceptional class:
- The C++ predefined exception class std::outofrange is derived from the std::logic_error base class.
- When an attempt is made to access an element or carry out an operation outside of the permitted range, errors are handled using this technique.
- Common Causes:
- Attempting to access an element outside the bounds of an array.
- Using a negative index or an index greater than or equal to the array size.
- Using an index that exceeds the size of a std::vector or other containers.
- Using an iterator thacpp tutorials beyond the valid range of elements.
- Reaching a nonexistent position when trying to access a container element.
- Using a container's at function and offering an out-of-range index.
- Using std::string::at with an incorrect index to try and extract characters from a string.
- In handling:
- You can use a try-catch block to catch a std::outofrange exception and manage it appropriately by handling it. It frequently entails putting up an error message and carrying out remedial measures.
- Preventing:
- It is a good idea to check a container's limits or size before accessing any of its elements to prevent out-of-range exceptions. If you want to make sure the access is inside allowed boundaries, you can use functions like size and empty .
Example:
Let's consider an example to demonstrate the usage of std::outofrange in C++:
#include <iostream>
#include <vector>
#include <stdexcept>
int main()
{
std::vector<int> myVector = {1, 2, 3};
try
{
int value = myVector.at(5); // This will throw an std::out_of_range exception.
std::cout << "Value: " << value << std::endl;
}
catch (const std::out_of_range &e)
{
std::cerr << "Out of Range error: " << e.what() << std::endl;
}
return 0;
}
Output:
Out of Range error: vector::_M_range_check: __n (which is 5) >= this->size() (which is 3)
Explanation:
In this case, the std::outofrange exception is thrown when an attempt is made to use myVector.at(5) to access an element at index 5 of the vector. This exception is caught and handled in the catch block.
- The header files required for input/output operations (\iostream>), vector usage (<vector>), and exception management (<stdexcept>) are included using the #include directives.
- The program's entrance point serves as its main
- std::vector{int> myVector = {1, 2, 3}; it creates a vector called myVector with the three integer members 1, 2, and 3.
- The code where an exception could be thrown is enclosed in a try block. The at function is used to attempt to access the element of the vector that is located at index 5, but since the vector doesn't have an element at that position, it will fail with a std::outofrange
- The thrown std::outofrange exception is caught by the catch block. The type of exception to catch is specified in the const std::outofrange &e section, where e is the variable that holds the captured exception.
- The what method is used in the catch block to output an error message with a description of the exception to the standard error stream (std::cerr).
- return 0; tells the main function to stop because the program has finished running successfully.