Давайте рассмотрим простой пример. Пользователю необходимо ввести команду. Формат может быть следующим: cmd i j или cmd, где cmd — предопределенный набор команд и номера i и j. Затем мы выполняем эту команду.
Что у меня есть, снизу вверх:
Код: Выделить всё
// utility function, converts string to enum
str_to_enum(string str, map s) -> enum
// may throw std::invalid_argument{"cannot convert " + str + " to enum"}
parse_line(string line)
tokens = split(line)
Cmd cmd = tokens[0]; // calls str_to_enum, lets the exception pass by
if (tokens.empty())
throw std::invalid_argument{"empty string as command"s};
if (...)
throw std::invalid_argument{cmd.spelling() + " does not take any argument."};
if (...)
throw std::invalid_argument{cmd.spelling() + " takes exactly 2 arguments."};
str_to_int(tokens[1])
str_to_int(tokens[2]) // throws std::out_of_range
main_loop() {
get_line(line);
try {
Full_cmd full_cmd = line; // calls parse_line, may throw
if (...)
throw std::invalid_argument{"Coordinates out of range"};
try {
execute_cmd(full_cmd); // may throw
}
catch (std::exception& e) {
cerr
Подробнее здесь: [url]https://stackoverflow.com/questions/39840119/how-to-get-from-exceptions-to-user-error-messages[/url]
Мобильная версия