HackerRank C++ Exceptional Server




Your friend set up a small computational server that performs complex calculations.
It has a function that takes 2 large numbers as its input and returns a numeric result. Unfortunately, there are various exceptions that may occur during execution.

Complete the code in your editor so that it prints appropriate error messages, should anything go wrong. The expected behavior is defined as follows:

If the compute function runs fine with the given arguments, then print the result of the function call.
If it fails to allocate the memory that it needs, print Not enough memory.
If any other standard C++ exception occurs, print Exception: S where s is the exception's error message.
If any non-standard exception occurs, print Other Exception.



  1. #include <iostream>
  2. #include <exception>
  3. #include <string>
  4. #include <stdexcept>
  5. #include <vector>
  6. #include <cmath>
  7. using namespace std;
  8. class Server {
  9. private:
  10. static int load;
  11. public:
  12. static int compute(long long A, long long B) {
  13. load += 1;
  14. if(A < 0) {
  15. throw std::invalid_argument("A is negative");
  16. }
  17. vector<int> v(A, 0);
  18. int real = -1, cmplx = sqrt(-1);
  19. if(B == 0) throw 0;
  20. real = (A/B)*real;
  21. int ans = v.at(B);
  22. return real + A - B*ans;
  23. }
  24. static int getLoad() {
  25. return load;
  26. }
  27. };
  28. int Server::load = 0;
  29. int main() {
  30. int T; cin >> T;
  31. while(T--) {
  32. long long A, B;
  33. cin >> A >> B;
  34. /* Enter your code here. */
  35. try {
  36. cout << Server::compute(A,B) << endl;
  37. }
  38. catch (bad_alloc& error) {
  39. cout << "Not enough memory" << endl;
  40. }
  41. catch (exception& error) {
  42. cout << "Exception: " << error.what() << endl;
  43. }
  44. catch (...) {
  45. cout << "Other Exception" << endl;
  46. }
  47. }
  48. cout << Server::getLoad() << endl;
  49. return 0;
  50. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube