fork download
  1. #include <iostream>
  2. #include <stdexcept> // For std::overflow_error
  3.  
  4. // Function to multiply two integers and check for overflow
  5. int multiply(int a, int b) {
  6. // We will check for overflow conditions
  7. if (a > 0 && b > 0 && a > (INT32_MAX / b)) {
  8. throw std::overflow_error("Overflow occurred while multiplying positive numbers");
  9. }
  10. if (a < 0 && b < 0 && a < (INT32_MAX / b)) {
  11. throw std::overflow_error("Overflow occurred while multiplying two negative numbers");
  12. }
  13. if (a > 0 && b < 0 && b < (INT32_MIN / a)) {
  14. throw std::overflow_error("Overflow occurred while multiplying positive by negative number");
  15. }
  16. if (a < 0 && b > 0 && a < (INT32_MIN / b)) {
  17. throw std::overflow_error("Overflow occurred while multiplying negative by positive number");
  18. }
  19.  
  20. return a * b;
  21. }
  22.  
  23. int main() {
  24. int x, y;
  25. std::cout << "Enter two integers: ";
  26. std::cin >> x >> y;
  27.  
  28. try {
  29. int result = multiply(x, y);
  30. std::cout << "Result: " << result << std::endl;
  31. } catch (const std::overflow_error& e) {
  32. std::cerr << "Caught an overflow_error exception: " << e.what() << std::endl;
  33. }
  34.  
  35. return 0;
  36. }
  37.  
Success #stdin #stdout #stderr 0s 5284KB
stdin
50000 50000
stdout
Enter two integers: 
stderr
Caught an overflow_error exception: Overflow occurred while multiplying positive numbers