Custom Exception for Negative Numbers
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.
-9
Error: Cannot calculate square root of a negative number
- -10^6 <= n <= 10^6
Hint 1
A custom exception is just a class that inherits from Exception — class NegativeValueError(Exception): pass.
Hint 2
raise NegativeValueError("...") inside the function stops it immediately and hands control to the except block.
Hint 3
n ** 0.5 computes a square root without needing to import math.
NegativeValueError is a custom exception class that inherits from Exception, giving a specific, self-explanatory name to this particular problem. calculatesquareroot(n) raises it (with a message) whenever n is negative; the calling code catches NegativeValueError specifically and prints a formatted error, while a valid n simply returns n ** 0.5.