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:

Since this is an Exception, the program could be written to handle it.

try{} and catch{}

To catch an Exception:

  1. Put code that might throw an Exception inside a try{} block.
  2. Put code that handles the Exception inside a catch{} block.

Here is the example program with code added to do this:

import java.util.* ;

public class SquareFix 
{

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

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

    try
    { 
      num    = scan.nextInt();      
      System.out.println("The square of " + num + " is " + num*num );
    } 

    catch ( InputMismatchException ex )
    { 
      System.out.println("You entered bad data." );
      System.out.println("Run the program again." );
    } 

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

  }
}

If a statement inside the try{} block throws a InputMismatchException, the catch{} block immediately starts running. The remaining statements in the try{} block are skipped. The reference variable ex refers to the Exception object. (However, this example does nothing with it.)

After the catch{} block is executed, execution continues with the statement that follows the catch{} block. Execution does not return to the try{} block.

QUESTION 5:

What does the program print for each input?

input 1:input 2:
Enter an integer: Rats Enter an integer: 12