🧠 Day 17: More Exceptions
📘 Goal:
Learn how to Make and throw your own exceptions in C++.
🎯 Problem Statement:
Write a class named Calculator with a method:
cpp
Copy
Edit
int power(int n int p);
This method should return n^p (n to the power of p).
If either n or p is negative the method should throw an exception with the message:
css
Copy
Edit
n and p should be non-negative
🔢 Input Format:
The first line contains an integer T the number of Check cases.
Each of the next T lines contains two space-separated integers n and p.
📤 Output Format:
For each Check case either print the result of n^p or print the exception message.
✅ Sample Input:
diff
Copy
Edit
4
3 5
2 4
-1 -2
-1 3
✅ Sample Output:
css
Copy
Edit
243
16
n and p should be non-negative
n and p should be non-negative
✅ C++ Answer:
cpp
Copy
Edit
#include
#include
#include
using namespace std;
class Calculator {
public:
int power(int n int p) {
if (n < 0 || p < 0)
throw invalid_argument("n and p should be non-negative");
return pow(n p);
}
};
int main() {
Calculator myCalculator;
int T;
cin >> T;
while (T--) {
int n p;
cin >> n >> p;
try {
int ans = myCalculator.power(n p);
cout << ans << endl;
} catch (exception& e) {
cout << e.what() << endl;
}
}
return 0;
}
🔍 important Concepts:
Exception handling with throw try catch.
Creating a method that can raise an exception.
Handling both valid and invalid input robustly.
Comments
Post a Comment