go to previous page   go to home page   go to next page

Answer:

input 1:input 2:
Enter an integer: Rats Enter an integer: 12
You entered bad data.
Run the program again.
Good-by
The square of 12 is 144
Good-by

Syntax of try{} and catch{}

Here is ONE form of the try/catch structure. (There are other forms soon to be discussed.)

try
{
  // statements which might throw 
  // various types of exceptions
}

catch ( SomeExceptionType ex )
{
  // statements to handle this
  // type of exception
}

catch ( AnotherExceptionType ex )
{
  // statements to handle this
  // type of exception
}

catch ( YetAnotherExceptionType ex )
{
  // statements to handle this
  // type of exception
}

// Statements following the structure

Here are a few syntax rules:

  1. The statements in the try block can include:
    • Statements that always work.
    • Statements that might cause an Exception of one type or another.
    • A throw statement that explicitly throws an Exception
  2. One or several catch blocks follow the try block.
    • Sometimes there can be no catch block. This will be discussed later in this chapter.
  3. Each catch block says which type of Exception it catches.
    • It does this in a one-item parameter list: ( ExceptionType parameter )
    • The parameter is a reference variable that will refer to the Exception object when it is caught.

QUESTION 6:

Is this code fragment OK?

    try
    {
      // various statements
    }

    catch (InputMismatchException ex )
    {
      // various statements
    }

    catch (IOException ex )
    {
      // various statements
    }

    System.out.println("Good-by" );

go to previous page   go to home page   go to next page