fork download
  1. #include <cmath> // for sqrt() function
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. // A modular square root function
  6. double MySqrt(double dX)
  7. {
  8. // If the user entered a negative number, this is an error condition
  9. if (dX < 0.0)
  10. throw "Can not take sqrt of negative number"; // throw exception of type char*
  11.  
  12. return sqrt(dX);
  13. }
  14.  
  15. int main()
  16. {
  17. cout << "Enter a number: ";
  18. double dX;
  19. cin >> dX;
  20.  
  21. try // Look for exceptions that occur within try block and route to attached catch block(s)
  22. {
  23. cout << "The sqrt of " << dX << " is " << MySqrt(dX) << endl;
  24. }
  25. catch (char* strException) // catch exceptions of type char*
  26. {
  27. cerr << "Error: " << strException << endl;
  28. }
  29. catch (...){
  30. cerr << "still got it :)" <<endl;
  31. }
  32. }
Success #stdin #stdout #stderr 0s 3476KB
stdin
Standard input is empty
stdout
Enter a number: 
stderr
still got it :)