Reputation: 33
I'm having trouble understanding the syntax of exceptions. I have a class template map<T>
that has to be able to throw an exception. The code bellow is correct and is used to catch the exception.
try
{
map<int> m;
m["everything"] = 42;
}
catch(map<int>::Uninitialized&)
{
cout << "Uninitialized map element!" << endl;
}
I was attempting to create a class derived from runtime_error and then throw it from my class. But it seems that my logic is flawed.
class Uninitialized : public runtime_error
{
public:
Uninitialized() : runtime_error("error") {}
};
T operator[] (const char index[]) const
{
throw Uninitialized();
return value;
}
Upvotes: 3
Views: 186
Reputation: 490178
The basic idea of what you're trying to do is certainly possible, so the exact problem you're encountering isn't entirely clear.
Here's a quick demo that does work, and does roughly what you seem to be trying:
#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";
}
}
Upvotes: 4
Reputation:
Let's say you are creating a map
type (although the standard library already provides one). You provide operator[]
, and want it to throw an exception every time someone attempts to access a non-existing key.
Create your exception class:
class unititialized_access : public std::runtime_error
{
// typical stuff
};
Then, within map<Key, Value>::operator[]
:
if (<key doesn't exist>)
throw unititialized_error("blah blah");
You catch the exception with:
try
{
m["foo"] = 42;
}
catch (const unitialized_error& e)
{
// do something
}
Upvotes: 0