c++exceptionerror-handlingruntime-errorlogic-error

How can I handle invalid data type exception and stop program execution?


I have a problem, I am studying exceptions and apparently I misunderstood something.

int n;
try {
  cout << "enter value: " << endl;
  cin >> n;
}
catch (exception& ex) {
  cerr << ex.what();
}
cout << n;

Output for any character literal: Output of the literal itself and zero.

I want to understand, if the user enters the wrong data type, can I somehow handle this input with an exception and tell the user that he is entering text, not a number? How can I understand where the exception throw occurs? How can I stop the program execution with the help of processing, otherwise the program continues to execute instructions...

I entered a non-numeric value and expected the program to tell me about it. I expected the program to stop executing after that.

also i tried this code

cout << "enter value: " << endl;
cin >> n;
if (!cin) throw exception();
try {
    cout << n;
}
catch (exception& ex) {
    cerr << ex.what();
}

Solution

  • you should check for error in code that is inside try block.

    based on your code ( looks like you are using std and endl)

    the code will be :

    try {
        std::cout << "Enter value \n";
        std::cin >> value;
        if(std::cin.fail())
           throw (/*what ever error you want*/);
        /*
         or 
         if(std::cin.fail())
           throw std::invalid_argument("your error text");
        */
    
    }
    catch(const char *e){
        std::cerr << "ERROR " << e << '\n';
        std::cin.clear();
        // send user to try for new input as you want
    }
    /*
    catch(const std::invalid_argument &err)
    {
        std::cerr << err.what() << '\n'; 
    }
    */