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;
}
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With