J2EEOnline J2EE 






Java Exceptions  «Prev 
Catching Exceptions in Java Exercise
Catching exceptions
The code on this page is for a stand-alone application that finds the square root of a number.
If the user supplied the proper command-line argument, the number that the program will use to find the square root, then the program works as expected. However, if the user forgot to supply a command-line argument, or if the argument is not a number, then the Java runtime will throw an exception. Here's the code:
class SqRoot {
 public static void main(String[] args) {
      double d = new Double(args[0]).doubleValue();
      double root = Math.sqrt(d);
      System.out.println(
          "The square root of " + d + " is " + root);
   }
}


Catch exceptions
Your mission in this exercise is to add exception handling to this code to catch the two exceptions referred to above.
If you are not sure what these exceptions are named, you can run the program and cause these errors to find the exceptions you need to handle.
Your exception-handling code can take any action you see fit.
One common way to handle this kind of exception in a character-mode program is to write a message to the standard output explaining what the user should do to get the program to work correctly.
Place your code into the text area below once it is working to your satisfaction.