jeudi 7 janvier 2021

C++ Handling error/exception that comes in multiple forms

Is there a better way to do this? I feel like this will be horrible to maintain.

const unsigned int set_max {32};
std::vector<unsigned int> base;
base.reserve(argc-1);
for (int i = 1; i < argc; ++i) {
  unsigned long tmp;
  try { tmp = std::stoul(argv[i], nullptr, 10); }
  catch (std::invalid_argument) { std::cerr << "Invalid base! Conversion failed.\n"; return -2; }
  catch (std::out_of_range) { std::cerr << "Invalid base! Too large.\n"; return -2; }
  if (tmp > std::numeric_limits<unsigned int>::max()) { std::cerr << "Invalid base! Too large.\n"; return -2; }
  if (tmp < 2) { std::cerr << "Invalid base! Must at least be 2.\n"; return -2; }
  if (tmp > set_max) { std::cerr << "Invalid base! Must be within " << set_max << ".\n"; return -2; }
  base.push_back(static_cast<unsigned int>(tmp));
}

Aucun commentaire:

Enregistrer un commentaire