Problem statement:
You are provided with a partially implemented class Server and a main function.
The Server class has a function compute that takes an integer as input and performs some computations.
However, the server is unreliable and can sometimes throw an exception.
Your task is to write the class implementation so that it handles the exception and prints "Exception: A is less than zero" when the input is negative.
Otherwise, it should print the result of the computation.
Sample Input:
The input consists of an integer T on the first line, which represents the number of test cases. This is followed by T lines, each containing an integer.
4
1
2
3
-1
Sample Output:
For each test case, print either "Exception: A is less than zero" (if the input is negative) or the result of the computation.
1
2
3
Exception: A is less than zero
Explanation:
In this example, we have four test cases:
The input is 1, so the computation is performed and the result is printed: 1.
The input is 2, so the computation is performed and the result is printed: 2.
The input is 3, so the computation is performed and the result is printed: 3.
The input is -1, which is negative. An exception is thrown and the error message "Exception: A is less than zero" is printed.
#include <iostream>
#include <stdexcept>
using namespace std;
class Server {
public:
static int compute(long long A) {
if (A < 0) {
throw invalid_argument("A is less than zero");
}
return A;
}
};
int main() {
int T;
cin >> T;
while (T--) {
long long A;
cin >> A;
try {
int result = Server::compute(A);
cout << result << endl;
} catch (const exception& e) {
cout << "Exception: " << e.what() << endl;
}
}
return 0;
}
Code Explanation
We start by including the necessary header files, including
The Server class is defined with a static function compute that takes a long long integer A as input and performs some computations.
Inside the compute function, we check if A is less than 0. If it is, we throw an invalid_argument exception with the error message "A is less than zero".
In the main() function, we read the number of test cases (T) using cin.
We then iterate T times and in each iteration, read an integer (A) using cin.
Inside a try-catch block, we call the compute() function of the Server class and store the result in a variable.
If an exception of type exception (or any of its derived classes) is thrown, the catch block is executed, and the error message is printed using e.what().
If no exception is thrown, the result of the computation is printed.
Finally, we return 0 to indicate successful execution.
The solution demonstrates the usage of exception handling in C++, specifically throwing and catching exceptions. It also handles input based on the given format and provides the expected output.
I hope this solution meets your requirements and provides a clear understanding of the problem and its solution!