Java Exceptions  «Prev  Next»

Java SquareRoot Application - Exercise

Modifying the SquareRoot Application

Objective: Modify the SquareRoot application to respond to negative numbers.

Instructions

In this exercise you will have the opportunity to modify the SquareRoot application to deal with negative numbers.
You should start this exercise with the following application.

class SquareRoot2 {
  public static void main(String[] args) {
    try {
      double number = 
        Double.valueOf(args[0]).doubleValue();
      double root   = compute(number);
      System.out.println(
        "The square root of " + number +
        " is " + root);
    }
    catch (ArrayIndexOutOfBoundsException e) {
      System.out.println(
        "Please supply a command-line argument");
    }
    catch (NumberFormatException e) {
      System.out.println(
        "The command-line argument must be a number");
    }
  }

  static double compute(double number) {
    return Math.sqrt(number);
  }
}


Implement the following changes to SquareRoot2.
  1. Define a new exception called ImaginaryNumberException.
  2. Add a throws clause to compute() that declares ImaginaryNumberException.
  3. In compute, throw an instance of ImaginaryNumberException if number is less than 0.
  4. In your main() method, catch ImaginaryNumberException and display a message.

Exercise Scoring

The full credit for this exercise is 5 points. To receive full credit, you will need to successfully create the source code for the application. You will submit your source code.

What to submit for this Exercise

In the text box below, cut and paste the modified source code for SquareRoot2. Click, Submit to submit the code.