In this constructor I am loading descriptions/area names from files, is this an effective way of error checking? I want to make sure that if for some reason there is an empty space in the text file or an error in loading, that it stops.
Feedback/criticism/props are welcome :)
// Using default exceptions - you could make your own, but that gets complicated.
#include <stdexcept>
board::board() {
std::ifstream load_description;
std::ifstream load_name;
// set the files to throw exceptions on 'bad' circumstances
load_description.exceptions(std::ifstream::failbit | std::ifstream::badbit);
load_name.exceptions(std::ifstream::failbit | std::ifstream::badbit);
load_description.open("map/description.txt");
load_name.open("map/name.txt");
for (int x = 0; x < board_upper_limit; ++x) {
for (int y = 0; y < board_upper_limit; ++y) {
std::string temp; // this gets overwritten regardless
load_name >> temp;
if (temp.empty())
throw std::runtime_error("Couldn't get board name!");
game_board[x][y].set_name(temp);
std::getline(load_description, temp);
if (temp.empty())
throw std::runtime_error("Couldn't get board description!");
game_board[x][y].set_description(temp);
}
}
// files close themselves here
}
Then you can see what happens when loading the board with a try...catch block, like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include "board.h"
#include <exception> // catch all generic exceptions
int main() {
try {
board b; // create an instance of the board
// use the board here
}
catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what();
return 1; // return an error
}
// ...
return 0;
}