C++ Programming Code Examples
C++ > Code Snippets Code Examples
Catch out_of_range exception
/* Catch out_of_range exception */
#include <iostream>
#include <vector>
#include <exception>
#include <stdexcept> // out_of_range exception
using namespace std;
int main( ) {
char carr[] = {'a', 'b', 'c', 'd', 'e'};
vector<char> v;
v.push_back('a');
v.push_back('b');
v.push_back('c');
v.push_back('d');
v.push_back('e');
try {
cout << v.at(10000) << '\n';
} catch(std::out_of_range& e) {
cerr << e.what( ) << '\n';
}
}
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
This class defines the type of objects thrown as exceptions to report an out-of-range error. Defines a type of object to be thrown as exception. It reports errors that are consequence of attempt to access elements out of defined range. It may be thrown by the member functions of std::bitset and std::basic_string, by std::stoi and std::stod families of functions, and by the bounds-checked member access functions (e.g. std::vector::at and std::map::at). It is a standard exception that can be thrown by programs. Some components of the standard library, such as vector, deque, string and bitset also throw exceptions of this type to signal arguments out of range.
Access element. Returns a reference to the element at position n in the vector. The function automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not (i.e., if n is greater than, or equal to, its size). This is in contrast with member operator[], that does not check against bounds. Function returns the element at the specified position in the container.
In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library. To use vectors, we need to include the vector header file in our program. The vector class provides various methods to perform different operations on vectors. Add Elements to a Vector: To add a single element into a vector, we use the push_back() function. It inserts an element into the end of the vector. Access Elements of a Vector: In C++, we use the index number to access the vector elements. Here, we use the at() function to access the element from the specified index.
Get string identifying exception. Returns a null terminated character sequence that may be used to identify the exception. The particular representation pointed by the returned value is implementation-defined. As a virtual function, derived classes may redefine this function so that specific values are returned. The exception::what() used to get string identifying exception. This function returns a null terminated character sequence that may be used to identify the exception. Below is the syntax for the same: This function does not accept any parameter. Function returns a pointer to a c-string with content related to the exception.
Add element at the end. Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element. This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity. push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1. This function does not return any value.
Standard output stream for errors. Object of class ostream that represents the standard error stream oriented to narrow characters (of type char). It corresponds to the C stream stderr. The standard error stream is a destination of characters determined by the environment. This destination may be shared by more than one standard object (such as cout or clog). As an object of class ostream, characters can be written to it either as formatted data using the insertion operator (operator<<) or as unformatted data, using member functions such as write. The object is declared in header <iostream> with external linkage and static duration: it lasts the entire duration of the program.
When executing C++ code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. When an error occurs, C++ will normally stop and generate an error message. The technical term for this is: C++ will throw an exception (throw an error). An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw. The try and catch keywords come in pairs:
C++ program ask to the user to enter the side length of a square to calculate and displaying the "area and perimeter" of the square. Enter length of a side of square and "calculate area"
In this control structure we have only one 'if' and one 'else', however we can have multiple 'else if' blocks. This is how it looks: If none of the 'condition is true' then these statements