fork download
  1. #include <iostream>
  2. #include <stdexcept>
  3.  
  4. int addition();
  5.  
  6. int main()
  7. {
  8. try //we can deal with exceptions that are thrown here
  9. {
  10. while(true)
  11. {
  12. std::cout << addition() << std::endl;
  13. }
  14. }
  15. catch(std::exception &e)
  16. {
  17. std::cerr << "Exception caught in main: " << e.what() << std::endl;
  18. }
  19. }
  20.  
  21. int addition()
  22. {
  23. int x, y;
  24. if(!(std::cin >> x >> y)) //check if the input operation succeeds
  25. {
  26. //throw an exception if it failed, since we can't do anything here
  27. throw std::runtime_error{"unable to read two integers"};
  28. }
  29. //otherwise, return normally
  30. return x + y;
  31. }
Success #stdin #stdout #stderr 0s 3464KB
stdin
1 2
3 b
2 5
stdout
3
stderr
Exception caught in main: unable to read two integers