Java Exceptions  «Prev  Next»

Adding Exception Handling - Exercise

Objective: Add exception handling to an application.

Instructions

The following application finds the square root of a number that is provided by the user as a command-line argument. If the user provides an appropriate argument, then the application works fine.
However, if the user does not provide an argument or if the argument is not a number, then an exception will be thrown.

class SquareRoot {

  public static void main(String[] args) {
    double number = Double.valueOf(args[0]).doubleValue();
    double root   = Math.sqrt(number);
    System.out.println("The square root of " + number +
      " is " + root);
  }
}

In this exercise you are to add exception handling to this code to catch the possible exceptions. To determine the name of these exceptions you can execute the application with no command-line argument and with an argument that is not a number. To handle the exceptions, you can display a message instructing the user on how to use the application correctly. For now, you do not need to worry about negative numbers. You will have an opportunity to address that situation in the next exercise.

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 SquareRoot.
Click Submit to submit the code.