Syntax of try{} and catch{}

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
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 throw an Exception of one type or another.

  2. One or several catch{} blocks follow the try() block.
    • Sometimes there can be no catch{} blocks. This will be discussed later in this chapter.

  3. Each catch{} block describes the 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 the following code fragment OK?

    try
    {
      // various statements
    }

    catch (InputMismatchException ex )
    {
      // various statements
    }

    catch (IOException ex )
    {
      // various statements
    }

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