Does a program have to catch and handle exceptions?

A good answer might be:

No---until this chapter none of the programs have done so.

NumberFormatException

Here is the program that had a problem with bad input data. The problem is that parseInt() received data it could not handle. It threw a NumberFormatException object back to the calling program (back to our program.)

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

    num    = Integer.parseInt( inData );     // convert inData to int

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

  }
}

Our program, however, does not have any code to deal with this exception, so the Java virtual machine stopped our program and printed out a trace of what went wrong.

QUESTION 4:

Could statements be added to handle this exception?

Click Here after you have answered the question