fork download
  1. #include <iostream>
  2. #include <stdexcept>
  3. using namespace std;
  4. int main()
  5. {
  6. int guess =0;
  7. cout << "Please guess a number from 1 to 5: " ;
  8. try
  9. {
  10. cin >> guess;
  11. if (guess<1 || guess>5)
  12. throw invalid_argument("Invalid guess \n");
  13. //If we throw an exception
  14. // it IMMEDIATELY gets out of try block
  15. cout << "Your guess is: " << guess << endl;
  16. }
  17. catch (invalid_argument & myInvalidObject)
  18. //notice reference
  19. {
  20. cout << myInvalidObject.what();
  21. }
  22. }//end of main
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Please guess a number from 1 to 5: Invalid guess