I want my program to throw exception on console window. But when exception occures Microsoft Visual C++ Runtime library dialog box shows up.

What can I do to stop visual studio from stopping execution of my program when an exception occues and let my program handle the exception?

I am using Visual Studio 2012 and with the following code.

#include<iostream>
#include<vector>
#include <stdexcept>

using namespace std;

int main()

try {
    vector<int> v;
    int data;
    while(cin >> data) v.push_back(data);
    for(unsigned int i = 0; i<=v.size(); i++) cout << v[i] << endl;

    return 0;
}
catch(out_of_range){
    cout << "Data fetch out of bound" << endl;
    return 1;
}
catch(...){
    cout << "Something went wrong!" << endl;
    return 2;
}

Edited 3 Years Ago by iamcreasy

That code doesn't compile, and even if it did it probably wouldn't throw an exception. If you were very lucky, you'd get a segFault, but probably not.

If your code throws an exception, and you think you can deal with it and carry on, catch it. What exception are you having trouble catching?

Why wouldn't it compile? It does compile on my side. Could you please tell me what went wrong?

I am trying to catch exception out_of_range using the following code :

for(unsigned int i = 0; i<=v.size(); i++) cout << v[i] << endl;

Here, the final iteration goes over the edge, and that should throw and out_of_range exception. I am trying to catch it an print an error on the console.

The code will compile, but the subscript operator for std::vector does not throw an exception. To get an out of range exception you must use the at member function.

@deceptikon Thanks. It solved the initial problem too.

Edited 3 Years Ago by iamcreasy

There's nothing stopping operator[] from throwing an exception, but I'd be a bit surprised if an implementation does so outside of debug mode. C++'s design model has been that you don't pay for what you don't use, and operator[] has traditionally been an unchecked operation. That's why the at member function was added, to provide a checked operation without forcing people to always pay for the possibility of a throw.

As such, you cannot depend on operator[] throwing. You can depend on at throwing.

This question has already been answered. Start a new discussion instead.