Skip to main content

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)

All Object Oriented Programming chapter 10 questions →