I've made a simple function that takes a vector as an argument. If the vector is empty, it throws a domain_error (I've included stdexcept).

I'm feeding it an empty vector from the main loop just to learn try...catch statements and when it catches the error, it's supposed to print something and carry on. Instead, however, it hangs on catching the error. I know I'm close, though, because if I use the step-through debugger in code::blocks and tell it to go to the next line, it continues as I'd expect it to. Why won't the executable do this on its own?

Sorry if this has been asked before, my search didn't come up with anything, and thanks in advance.

#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <stdexcept>
#include <cstdlib>

using namespace std;

double get_median(vector<double> vec)
{
    if (vec.size() == 0)
        throw domain_error("Can't find median of empty vector");
    return 5.5;
}

int main()
{
    vector<double> vec;
    try
    {
        double med = get_median(vec);
    }
    catch (domain_error& e)
    {
        cout << "exception handled" << endl;
    }
    system("pause");
    return 0;
}

In your catch statement, you referred to e but you never used it. Instead of

cout << "exception handled" << endl;

try

cout << e.what() << endl;

That should display the error string that you threw. If you want to specify it as an error, you could use cerr instead of cout as well.

In your catch statement, you referred to e but you never used it. Instead of

cout << "exception handled" << endl;

try

cout << e.what() << endl;

That should display the error string that you threw. If you want to specify it as an error, you could use cerr instead of cout as well.

I know I currently have an unused variable. This is a small sample to illustrate the problem I'm having.

cout << e.what() << endl;

suffers from the same problem, as does

cerr << e.what() << endl;

The unused variable is not the issue here. The issue is that the code in my catch block isn't getting executed unless I make it continue in the step-through editor.

I stand corrected. Apparently, Code::Blocks does that on exception. If I just build the binary and run it from outside of Code::Blocks, it does exactly what's expected of it. False alarm, my fault.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.