InputMismatchException

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 ― none of our previous example programs have done this.

InputMismatchException

Here is the example program. When the user entered "rats", the nextInt() method threw a InputMismatchException object.

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 );
  }
}

This program lacks code to deal with this Exception. So, when nextInt() threw an Exception, the program threw the Exception 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?