Java Exceptions  «Prev 

Java throwing exceptions Exercise

Throwing exceptions

Objective:
In this exercise, the square root program written earlier will be extended to detect when the answer might be an imaginary number. (An imaginary number is the square root of a negative number.) Here is some partially implemented code that will need to be completed:

class SqRoot2 {
 public static void main(String[] args) {
   try {
     double d = getInput(args[0]);
     double root = Math.sqrt(d);
     System.out.println(
       "The square root of " + d + " is " + root);
   } 
   catch (NumberFormatException e) {
     System.out.println("Be sure to enter a number.");
   }
   catch (ArrayIndexOutOfBoundsException e) {
     System.out.println("Enter number as first parameter.");
   }
   catch (ImNumberException e) {
     System.out.println("Result will be imaginary number.");
   } 
 }
 static double getInput(String s) throws ImNumberException {
   double d = new Double(s).doubleValue();
   // Throw an ImNumberException if d is less than 0
   return d;
 }
}
// Define an ImNuberException class

Handle exceptions

As the bold portions of the above listing illustrate, you should define a new class called ImNumberException that is capable of acting like an exception. Then, if the value for what the user has supplied is a negative number, throw an instance of this exception.
Place your code into the text area below once it is working smoothly.