User-friendly Code

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:

No. You only write the catch{} blocks for the Exceptions you wish to handle. Other Exceptions are thrown to the caller of the method that caused the exception.

User-friendly Code

Exception handling is important for user-friendly programs. Here is the compute-the-square program again, this time written so that the user is prompted again if the input is bad:

import java.util.* ;

public class SquareUser 
{

  public static void main ( String[] a ) 
  {
    Scanner scan = new Scanner( System.in  );
    int num = 0 ;
    boolean goodData = false;

    while ( !goodData )
    {
      System.out.print("Enter an integer: ");
      
      try
      {
        num = scan.nextInt();      
        goodData = true;
      } 

      catch (InputMismatchException  ex )
      { 
        System.out.println("You entered bad data." );
        System.out.println("Please try again./n" );
        String flush = scan.next();
      }
    }

    System.out.println("The square of " + num + " is " + num*num );

  }
}

This is a common style for reading user input. It would be useful to copy, save, and run this program.

QUESTION 8:

Could the following statement be moved into the program's try{} block?

System.out.println("Enter an integer:");