Beginning Programming with Java For Dummies
Book image
Explore Book Buy On Amazon

Whenever you use a statement that might throw an exception in Java, you should write special code to anticipate and catch the exception. That way, your program won’t crash if the exception occurs.

You catch an exception by using a try statement, which has this general form:

try
{
<i> </i><i>statements that can throw exceptions</i>
}
catch (<i>exception-type identifier</i>)
{
<i> </i><i>statements executed when exception is thrown</i>
}

Here, you place the statements that might throw an exception within a try block. Then you catch the exception with a catch block.

Here are a few things to note about try statements:

  • You can code more than one catch block. That way, if the statements in the try block might throw more than one type of exception, you can catch each type of exception in a separate catch block.

  • For scoping purposes, the try block is its own self-contained block, separate from the catch block. As a result, any variables you declare in the try block are not visible to the catch block. If you want them to be, declare them immediately before the try statement.

  • You can also code a special block (called a finally block) after all the catch blocks. For more information about coding finally blocks.

  • The various exception classes in the Java API are defined in different packages. If you use an exception class that isn’t defined in the standard java.lang package that’s always available, you need to provide an import statement for the package that defines the exception class.

A simple example

To illustrate how to provide for an exception, here’s a program that divides two numbers and uses a try/catch statement to catch an exception if the second number turns out to be zero:

public class DivideByZero
{
 public static void main(String[] args)
 {
  int a = 5;
  int b = 0;   // you know this won’t work
  try
  {
   int c = a / b; // but you try it anyway
  }
  catch (ArithmeticException e)
  {
   System.out.println("Oops, you can’t "
    + "divide by zero.");
  }
 }
}

Here, the division occurs within a try block, and a catch block handles ArithmeticException. ArithmethicException is defined by java.lang, so an import statement for it isn’t necessary.

When you run this program, the following is displayed on the console:

Oops, you can’t divide by zero.

There’s nothing else to see here.

Another example

Here is a simple example of a program that uses a method to get a valid integer from the user. If the user enters a value that isn’t a valid integer, the catch block catches the error and forces the loop to repeat.

import java.util.*;
public class GetInteger
{
 static Scanner sc = new Scanner(System.in);
 public static void main(String[] args)
 {
  System.out.print("Enter an integer: ");
  int i = GetAnInteger();
  System.out.println("You entered " + i);
 }
 public static int GetAnInteger()
 {
  while (true)
  {
   try
   {
    return sc.nextInt();
   }
   catch (InputMismatchException e)
   {
    sc.next();
    System.out.print("That’s not "
     + "an integer. Try again: ");
   }
  }
 }
}

Here the statement that gets the input from the user and returns it to the methods called is coded within the try block. If the user enters a valid integer, this statement is the only one in this method that gets executed.

If the user enters data that can’t be converted to an integer, however, the nextInt method throws an InputMismatchException. Then this exception is intercepted by the catch block — which disposes of the user’s incorrect input by calling the next method, as well as by displaying an error message. Then the while loop repeats.

Here’s what the console might look like for a typical execution of this program:

Enter an integer: <b>three</b>
That’s not an integer. Try again: 3.001
That’s not an integer. Try again: 3
You entered 3

Here are a couple other things to note about this program:

  • The import statement specifies java.util.* to import all the classes from the java.util package. That way, the InputMismatchException class is imported.

  • The next method must be called in the catch block to dispose of the user’s invalid input because the nextInt method leaves the input value in the Scanner’s input stream if an InputMismatchException is thrown. If you omit the statement that calls next, the while loop keeps reading it, throws an exception, and displays an error message in an infinite loop.

    This error was found the hard way. (The only way to make it stop is to close the console window.)

    image0.jpg

About This Article

This article can be found in the category: