Skip to content
C

Custom Exception for Negative Numbers

Mediumpython

Create a custom exception NegativeValueError, and write a function calculatesquareroot(n) that raises it if n is negative, otherwise returns the square root.

What the problem means: instead of returning some placeholder value for an invalid input, deliberately raise a clearly-named exception so the caller knows exactly what went wrong.

Approach: define class NegativeValueError(Exception): pass, then inside calculatesquareroot(n), raise it (with a message) if n < 0, otherwise return n ** 0.5. Catch it where the function is called and print a formatted error.

Input: One line: a number n.

Output: One line: the square root, or Error: Cannot calculate square root of a negative number if n is negative.

Input (stdin)

Output

Run your code to see output here...