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

Answer:

No – none of our previous example programs have done this.


InputMismatchException

import java.util.* ;

public class Square
{

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

    System.out.print("Enter an integer: ");
    num = scan.nextInt();      
    System.out.println("The square of " + num + " is " + num*num );
  }
}

Above is the example program. When the program asked for input, the user entered "rats". The nextInt() method could not read that as an integer and threw an InputMismatchException object.

This program lacks code to deal with Exceptions. So, when nextInt() threw an Exception, it went to the Java virtual machine. Then the Java virtual machine caught the Exception, stopped the program, and printed a trace of what went wrong.


QUESTION 4:

Could statements be added to handle this Exception?


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