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

Answer:

Yes.


IndexOutOfBoundsException

Exception objects contain data and methods, as does any object. Here are some methods:

A catch{} block can use these methods to write an informative error message to the monitor.

The example program asks the user for an integer and for an array index where it is to be placed.

Only indexes 0 through 9 are allowed. Any other index causes an IndexOutOfBoundsException.


import java.util.* ;

public class IndexPractice
{
  public static void main ( String[] a )
  {
    Scanner scan = new Scanner( System.in );
    int data=0, slot=0 ;
    int[] value = new int[10];

    try
    { 
      System.out.print("Enter the data: ");
      data = scan.nextInt();
      System.out.print("Enter the array index: ");
      slot = scan.nextInt();
      value[slot] = data;
    }

    catch (InputMismatchException ex )
    {  
      System.out.println("This is your problem: " +  ex.getMessage()   
          + "\nHere is where it happened:\n");
       ex.printStackTrace();  
    } 

    catch (IndexOutOfBoundsException ex )
    {  
       System.out.println("This is your problem: " +  ex.getMessage()   
          + "\nHere is where it happened:\n");
       ex.printStackTrace(); 
     } 

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

QUESTION 3:

If the user enters:

Enter the data: 8
Enter the array index: 10

will an exception be thrown?