Greetings.
I am learning about exception handling.
The following code will give an out-of-range error. When I tried to execute the code, it pops out the "Debug Assertion Failed" window. However whatever specified in catch(){} was not executed.
#include <vector>
#include <iostream>
usingnamespace std;
int main()
{
vector<int> v;
for (int i; cin >> i;)
v.push_back(i);
try
{
for (int i = 0; i <= v.size(); i++)
cout << v[i] << endl;
}
catch(out_of_range& oor)
{
cerr << "out of range error detected" << '\n'<<oor.what()<<endl;
}
system("pause");
return 0;
}
What needs to be done, if I want the actions specified in catch(){} to be executed and show up in console terminal and not show the "Debug Assertion Failed" dialog box?
#include <iostream>
#include <vector>
usingnamespace std;
int main()
{
vector<int> v;
//for (int lc{}, input; lc < 3; lc++)
//{
// std::cout << " Enter number " << lc + 1 << ": "; // <--- The "cin" ALWAYS needs a prompt.
// std::cin >> input;
// v.push_back(input);
//}
for (int lc{}; lc < 5; lc++) // <--- Quick way for testing. Delete When finished.
{
v.push_back(lc);
}
try
{
for (int i = 0; i <= v.size(); i++)
cout << v.at(i) << endl; // <--- Changed.
}
catch (const std::exception& e)
{
cerr << "\n Out of range error detected\n " << e.what() << '\n'; // <--- Changed.
}
//system("pause");
// <--- Keeps console window open when running in debug mode on Visual Studio. Or a good way to pause the program.
// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
//std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue: ";
std::cin.get();
return 0; // <--- Not required, but makes a good break point.
}
// This is code I found for testing. https://en.cppreference.com/w/cpp/language/try_catch
//try
//{
// std::cout << "Creating a vector of size 5... \n";
// std::vector<int> v(5);
// std::cout << "Accessing the 11th element of the vector...\n";
// std::cout << v.at(10); // vector::at() throws std::out_of_range
//}
//catch (const std::exception& e)
//{ // caught by reference to base
// std::cout << " a standard exception was caught, with message '"
// << e.what() << "'\n";
//}
Normally you do not need to use the ".at()" in a for loop, but since the (<=) does 1 more loop than needed the ".at()" throws an exception that the "catch" will catch.
@OP,
did you run the code in DEBUG mode in Visual Studio?
In DEBUG mode the vector subscript operator in VS doesn't throw exceptions you can catch but uses assertions.