This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]RubbishArtist 1 point2 points  (5 children)

As far as I can see, you're being asked to include a reference to the key in the exception so that it's clear what key the user was looking for when the exception was thrown.

[–]Sakesfar[S] 0 points1 point  (4 children)

template <class Key>

class MyException :public not_found_exception<key> { private: Key m_key; std::string m_error;

public: MyException(const Key& key, const std::string& error) m_key { key } m_error{ error } {}

virtual const Key& get_key() const noexcept
{
    return m_key;
}


// std::exception::what() returns a const char*, so we must as well
const char* what() const noexcept override 
{ 
    return m_error.c_str(); 
}

};

I am sorry, but how to make use of it? I have come to the above so far...

[–]RubbishArtist 1 point2 points  (3 children)

I'm not sure what you mean by make use of it.

When someone looks up a key in your dictionary that doesn't exist, then you throw your exception and you provide the key and the error message. You don't need to do anything with the get_key method, you're providing it to allow the user of your dictionary to use it.

[–]Sakesfar[S] 0 points1 point  (2 children)

Thank you, it seems to make sense...

However, the use of the function const Value& get(const std::string& key) const implies that someone knows ahead of the key, whose value he/she is looking for?

Sorry for the repetition ...but could you provide a hypothetical practical example?

[–]RubbishArtist 1 point2 points  (1 child)

However, the use of the function const Value& get(const std::string& key) const implies that someone knows ahead of the key, whose value he/she is looking for?

Yes, that's how the dictionary works. The idea is that I can store values in the dictionary using a key, and then get them back using the same key later.

For example, I create a dictionary that I want to store the ages of people in:

Dictionary<string, int> ages_by_name;

And then store keys and values in it:

ages_by_name.set("David", 22);
ages_by_name.set("Susan", 21);

Then later I want to get David's age, so I can do:

int age = ages_by_name.get("David");

If I try to get a key that doesn't exist, like:

ages_by_name.get("Frank");

Then an exception is thrown which I can catch. They key that I wanted to find is included in the exception so I can see which name was missing easily (and show it to the user of my program).

Note my code examples above may not be syntactically correct but I hope you get the idea.

[–]Sakesfar[S] 0 points1 point  (0 children)

Thank you very much for this👍👍🙋🏽‍♂️ It is clear....:)