3.1. Warm Up

Before we get into the details of exception handling in Java, let’s do some review.

Test Yourself

Consider the complete Java program below:

 1import java.util.Scanner;
 2
 3public class Exceptions {
 4   public static void main(String[] args) {
 5       String myString = "Go Dawgs!";
 6       Scanner input = new Scanner(System.in);
 7
 8       System.out.println("Please enter a valid index (0-8): ");
 9       int index = input.nextInt();
10
11       char selectedChar = myString.charAt(index);
12       System.out.println("Your selected character: " + selectedChar);
13
14       System.out.println("Program Completed");
15   } // main
16} // Exceptions
  • What is the exact output of this program if the user enters 1?

  • What happens if the user enters 9?

Test Yourself Solution (Don’t open until completing the question above)
  • If the user enters a 1, the program will complete without an exception. The exact output is:

    Please enter a valid index (0-8):
    1
    Your selected character: o
    Program Completed
    
  • If the user enters a 9, the index is out of bounds which will cause a runtime exception. In this situation, the program fails at line 11 and lines 12-14 will not execute.

Thought Exercise

How could you adjust the program above to avoid the crash and subsequent exception message?