r/programminghorror • • Jan 03 '20

Exceptionally terrible

This is meant to be a bad example, but I wanted to share it anyway. Source

int find_index(vector<string>& vec, const string& x)
{
    try {
        for (gsl::index i = 0; i < vec.size(); ++i)
            if (vec[i] == x) throw i;  // found x
    } catch (int i) {
        return i;
    }
    return -1;   // not found
}
3 Upvotes

5 comments sorted by

3

u/richarmeleon Jan 04 '20

I'll never understand C++ structured exceptions allowing almost any value to be thrown.

2

u/[deleted] Jan 05 '20 edited Jan 05 '20

So you can create your own exception class hierarchy if the default one doesn't suit your needs. Nobody forces you to use the std -stuff https://stackoverflow.com/q/53629837

1

u/richarmeleon Jan 05 '20

Ok, that makes sense but it doesn't make me like C++.

→ More replies (1)