I am getting the error "Constructor NegativeException() is undefined" in my Root class. Can anyone point me in the right direction?
Attempting to get the square root of a negative number is an illegal mathematical operation. Java supplies a square root method in the Math class i.e.:
public static double sqrt(double a)
This method returns a special constant double value (NaN i.e. not a number) if the parameter had a negative value. It does not throw an exception.
a) Write the Java code for a custom exception class to represent an exception resulting from an attempt to get the square root of a negative number (double). This class should inherit from ArithmeticException, and only needs a simple constructor whose parameter holds the value of the number which has caused the exception.
b) Write the Java code for a Root class which contains a sqrt method which will return the square root of a double passed to it as a parameter or throw an exception of the type defined in (a) if the parameter is negative. It should call Math.sqrt() if no exception occurs.
c) Write the code for a main method in a test class which calls the method defined in (b), inside a try/catch block.
'throw new NegativeException();' fails to compile as you don't have a no-arg constructor in NegativeException class. You need to modify the call as 'throw new NegativeException(number);'.
Your Root class won't compile even after this as its superclass NegativeException doesn't have a no-arg constructor. Since you didn't define a constructor for Root class, compiler provides a default one with an implicit call to super(), where it fails. In this case, Root doesn't need to extend from NegativeException.
Why does Root extend NegativeException? That looks totally inappropriate.
I would have thought NegativeException should extend IllegalArgumentException, but I would point out that the sqrt() method will accept a negative argument. Have a look at its documentation, and you will find out what it returns for a negative argument.
Thanks Guys, I made the changes suggested and the exception get thrown correctly now. Richie, this is a past paper question i'm working from, if the square root of a negative number returns something does this mean the question is incorrect?
The last part of the question asks to use a try,catch block, can I add this even when iv'e manually thrown the exception already?
Did you look at the documentation? Here it is. You have a choice between throwing an Exception for a negative number, returning what the Math class method does, or converting it to a positive number and returning a real number. Obviously different people will make different choices.
You can put a try-catch in the method where you call the root method from. Don’t throw and catch the same Exception in the same place.