Skip to article frontmatterSkip to article content

Comment gérer les erreurs (utilisateurs) ?

IUT d'Orsay, Université Paris-Saclay

D’abord, un point sur Git.

Structure de donnée de l’historique Git

Gestion des erreurs

Programmation robuste

Input validation

Pour certaines erreurs, il n’est pas nécessaire d’arrêter l’exécution du programme et il suffit de valider l’entrée de l’utilisateur avant de passer à l’étape suivante.

#include <iostream>
#include <limits> // for numeric_limits
#include <stdexcept>

int getPositiveInteger() {
    int userInput;
    int attempts = 0;
    const int maxAttempts = 5;

    while (attempts < maxAttempts) {
        std::cout << "Enter a positive integer: ";
        std::cin >> userInput;

        if (std::cin.fail() || userInput <= 0) { // cin.fail() is true if user inputs non-integer value or the value is too large
            std::cin.clear(); // cin.clear() resets the state of cin if it was in fail state
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Clear the buffer until it reaches end of line character '\n'.
            attempts++;
            std::cout << "Invalid input. Please try again. For example: 1" << std::endl;
            std::cout << maxAttempts - attempts << " left." << std::endl;
        } else {
            return userInput;
        }
    }
    
    // Explained below
    throw std::invalid_argument("Maximum attempts reached.");
}

try, throw, catch