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

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" );
        scan.nextLine();
      }
    }

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

  }
}

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


QUESTION 8:

What is the function of

scan.nextLine();

in the catch block?


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