JensB
JensB

Reputation: 939

How can I throw errors with custom error messages?

I have a function that allocates a text font on the heap from a filename. It looks like this:

std::unique_ptr<sf::Font> newFont(std::string&& fileName)
{
    auto font = std::make_unique<sf::Font>();
    if (!font->loadFromFile(fileName))
    {
        exit(0);
    }
    return font;

}

Someone on Stack Exchange - Code Review told me that I needed better error messages, since my program just silently exits if the file is not found. But since I'm writing a game, I'm not using a console window for output. I was thinking that maybe I could throw some kind of custom compiler error that triggers when the file is not found. Something like "Unable to allocate font: <font_path>". Is there a way to do this, or should I solve this some other way?

Upvotes: 0

Views: 132

Answers (1)

Jan Schultke
Jan Schultke

Reputation: 39444

Exceptions are what you are looking for:

std::unique_ptr<sf::Font> newFont(std::string&& fileName) noexcept(false)
{
    auto font = std::make_unique<sf::Font>();
    if (!font->loadFromFile(fileName))
    {
        throw std::runtime_error("Unable to allocate font: " + fileName);
    }
    return font;
}

Now we can print error messages using a try-catch block:

int main() {
    std::unique_ptr<sf::Font> font;
    try {   
        font = newFont("myfont.ttf");
    } catch ( const std::exception & ex ) {
        PRINT_ERROR(ex.what());
        return 1;
    }
    // do something with font ...
}

Normally you could implement PRINT_ERROR by just printing to std::cerr, but since you don't have a console to print to, you will need to do something else with the error message. Options include:

  • creating a log file and printing errors to the log using std::ofstream
  • displaying the error messages directly in your game

Upvotes: 1

Related Questions