- 2072 Chaitra · 5 marks
Square root with exception
Short answer
Define a class NegativeNumber to carry the invalid value. In findSqrt() throw NegativeNumber(x) if x<0. In main(), catch NegativeNumber and print error; also check for non-numeric input with cin.
Write a program to find the square root of given number. Check the validity of input number and raise the exception as per requirement.
Validity rule: the square root of a negative number is not real, so a negative input raises an exception. Non-numeric input is also checked.
#include <iostream>
#include <cmath>
using namespace std;
class NegativeNumber {
public:
double value;
NegativeNumber(double v) : value(v) {}
};
double findSqrt(double x) {
if (x < 0)
throw NegativeNumber(x); // raise exception
return sqrt(x);
}
int main() {
double n;
cout << "Enter a number: ";
if (!(cin >> n)) {
cout << "Invalid input: not a number\n";
return 1;
}
try {
cout << "Square root = " << findSqrt(n) << endl;
}
catch (NegativeNumber e) {
cout << "Error: cannot find square root of negative number "
<< e.value << endl;
}
return 0;
}
Sample runs
Enter a number: 49
Square root = 7
Enter a number: -9
Error: cannot find square root of negative number -9
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Exception with argument and specification program · Object Oriented Programming, chapter 10
- Prime number program: procedural and OOP · Object Oriented Programming, chapter 1
- File stream; student binary file program · Object Oriented Programming, chapter 8
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6
- Square root circuit and √((V1V2)²+(V3V4)²) · Advanced Electronics, chapter 6 · asked 2×
- Root-locus design: 8 samples per cycle, T = 0.2 s · Digital Control System, chapter 4
- Check triangular number · Computer Programming, chapter 5
- Square root of time method for cv · Soil Mechanics, chapter 9