C ++ Exception Syntax

I'm having trouble understanding exception syntax. I have a class template map<T>that should be able to throw an exception. The code below complies with the rule and is used to throw an exception.

try
{       
    map<int> m;
    m["everything"] = 42;
}
catch(map<int>::Uninitialized&)
{
    cout << "Uninitialized map element!" << endl;
}

I tried to create a class derived from runtime_error and then threw it out of my class. But it seems my logic is wrong.

class Uninitialized : public runtime_error
{
public:
    Uninitialized() : runtime_error("error") {}
};

T operator[] (const char index[]) const
{
    throw Uninitialized();
    return value;
}
+3
source share
2 answers

The basic idea of ​​what you are trying to do is of course possible, so the specific problem you are facing is not entirely clear.

Here is a brief demo that really works, and does something you try:

#include <stdexcept>
#include <iostream>

template <class T>
class map { 
public:
    class Uninitialized : public std::runtime_error
    {
    public:
        Uninitialized() : runtime_error("error") {}
    };

    T operator[](const char index[]) const
    {
        throw Uninitialized();
        return T();
    }
};

int main(){ 
    map<int> m;
    try {
        auto foo = m["a"];
    }
    catch (map<int>::Uninitialized &m) {
        std::cerr << "Caught exception:" << m.what()<< "\n";
    }
}
+4
source

, map ( ). operator[] , , - .

:

class unititialized_access : public std::runtime_error
{
    // typical stuff
};

map<Key, Value>::operator[]:

if (<key doesn't exist>)
    throw unititialized_error("blah blah");

:

try
{
    m["foo"] = 42;
}
catch (const unitialized_error& e)
{
    // do something
}
0

All Articles