Computer scienceProgramming languagesC++Errors, debugging, and exceptions

Exception Handling

Theory

Prime number

Report a typo

Below C++ program checks if a given positive integer is a prime number. But there are some errors in custom exception handling which ensure that negative input is not accepted. You have to fix those errors and modify the code such that error messages for negative or zero input is correctly printed.

Sample Input 1:

0

Sample Output 1:

Error: Negative or zero input is not allowed. Please enter a positive integer.
Write a program in C++
#include <iostream>
using namespace std;

int main() {
int num;
cin >> num;

throw {
if (num < 0) {
throw "Negative or zero input is not allowed. Please enter a positive integer.";
}

// Do not change the below code
bool isPrime = true;
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
isPrime = false;
break;
}
}
// Do not change the above code

if () {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}
} catch () {

}

return 0;
}

Create a free account to access the full topic