Homework 5 Notes
1. Instructions
This assignment is about error handling and fault detection to make sure we handling errors gracefully and not crashing the program. The assignment is pretty straightforward, but here is an example:
#include <stdexcept>
void UserNotification::Notify(const Notification category) const
{
const auto callback = m_callbacks.find(category);
if (callback == m_callbacks.end())
{
throw std::invalid_argument("Invalid category");
}
if (const auto* callbackFunc = std::get_if<std::function<void()>>(&callback->second))
{
(*callbackFunc)();
}
else
{
throw std::invalid_argument("No registered callback");
}
}
Here, we are throwing an exception if the category is invalid or if there is no registered callback.
Another example is in Dungeon::FindCave()
:
const std::shared_ptr<Cave>& Dungeon::FindCave(const int caveId)
{
const auto caveItr = m_caves.find(caveId);
if (caveItr == m_caves.end())
{
throw std::invalid_argument("Invalid caveId: " + std::to_string(caveId));
}
return caveItr->second;
}
This exception is later caught in main()
:
if (command == "m" || command == "M" || command == "move" || command == "MOVE")
{
if (stringTokens.size() < 2)
{
std::cout << "A Move command must be followed by the destination cave id." << std::endl;
continue;
}
// Second token is a destination.
try
{
const auto destCave = std::stoi(stringTokens[1]);
dungeon.MakeMove(HuntTheWumpus::DungeonMove::Move, { destCave });
}
catch (const std::exception&)
{
std::cout << "A Move command must be followed by a cave number. \"" << stringTokens[1] << "\" could not be converted to a valid tunnel to go through." << std::endl;
}
}
Here, we are catching the exception and printing out a message to the user.