cin exceptions c++

#include <iostream>
#include <limits>

int main() {
    // Save the current state of cin
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);

    // Initialize variables
    int number;

    // Set up exception handling for cin
    try {
        // Prompt the user for input
        std::cout << "Enter an integer: ";

        // Enable exception throwing for invalid input
        std::cin.exceptions(std::ios_base::failbit);

        // Input the integer
        std::cin >> number;

        // Output the entered integer
        std::cout << "You entered: " << number << std::endl;
    } catch (const std::ios_base::failure& e) {
        // Handle the exception when invalid input is encountered
        std::cerr << "Invalid input. Please enter a valid integer." << std::endl;

        // Clear the error state of cin
        std::cin.clear();

        // Discard the invalid input
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

    return 0;
}