Could statements be added to handle this exception?

A good answer might be:

Since this is an exception, the program can handle it (with the right code.)

try and catch

To catch an exception you usually:

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

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

import java.lang.* ;
import java.io.* ;

public class Square 
{

  public static void main ( String[] a ) throws IOException
  {
    BufferedReader stdin = 
        new BufferedReader ( new InputStreamReader( System.in ) );
 
    String inData;
    int    num ;

    System.out.println("Enter an integer:");
    inData = stdin.readLine();

    try
    {
      num    = Integer.parseInt( inData );
      System.out.println("The square of " + inData + " is " + num*num );
    }

    catch (NumberFormatException 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 NumberFormatException, the catch{} block immediately starts running. The reference ex refers to an object that represents the exception. (Our example does nothing with it.)

After completing the catch{} block, execution continues with the statement that follows it. (Execution does not return to the try{} block.)

QUESTION 5:

What does the program print for each input?

input 1:input 2:
Rats 12
 
 
 
 
 
 
 
 
Click Here after you have answered the question