Return to lecture notes index

15-100 Lecture 18 (Friday, October 13, 2006)

Try and Catch

So we've learned how to throw new exceptions, but if we just throw the exception, our program is going to crash because the exception isn't handled.

So how do we go about reporting the error to the user in a more descriptive way, without actually crashing our program? We use the Java keyword try, which tells Java that the code inside the try block (inside the scope of the squiggly braces opened after the keyword 'try') might throw an exception

However, the try block in itself is not enough to handle the exception that might be thrown. If exceptions are being thrown, we must "catch" them. The "try" block alerts Java that it must be ready to catch an exception; we now need a "catch" block to tell it what to do when/if it does catch an exception.

When we close the try block by adding the close-squiggly brace, we then open a "catch" block as shown below. Inside the parentheses, we specify what type of exception this catch block is designed to catch, and of course, just like any other argument, we need to give this Exception variable a name (e.g., nfe, ioe). Inside the squiggly braces for the catch block, we tell Java what to do if it catches this type of exception in the try block above. It's a good idea to use these catch blocks to tell the user what they did wrong (why the exception was thrown). Also, note that we can have a separate catch block for each type of exception that might be thrown inside the try block.

  import java.io.*;
import java.util.*;


class Menu {

  private class MenuChoiceException extends Exception {

    public MenuChoiceException (String message) {
      super(message);
    }
  } 

  
  private static final int MAX_TRIES = 3;
  
  public char getChoice(String choices) throws MenuChoiceException {
    Scanner keyboard = new Scanner (System.in);
  
    for (int tryCount=0; tryCount < MAX_TRIES; tryCount++) {
      System.out.println ("F)irst name");
      System.out.println ("M)iddle name");
      System.out.println ("L)ast name");
      System.out.println ("");
      System.out.print ("Choice> ");
    
      char choice = keyboard.nextLine().toUpperCase().charAt(0);
    
      for (int index=0; index < choices.length(); index++) 
        if (choice == choices.charAt(index))
          return choice;
    
      System.out.println ("Invalid choice. Please try again!");
    }
   
    throw new MenuChoiceException ("" + MAX_TRIES + " retries");
  }
 
 public static void main (String[] args) {
   
   Menu exampleMenu = new Menu();
   String choices = "FML";
   char choice;
   
   while (true) {
     try {
       choice = exampleMenu.getChoice(choices);
     }
     catch (Menu.MenuChoiceException mce) {
       System.out.print ("Too many tries -- program ending: ");
       System.out.println (mce.getMessage());
       return;
     }
      
     switch (choice) {
       case 'F': System.out.println ("Greg");
                 break; 
       case 'M': System.out.println ("Michael");
                 break;
       case 'L': System.out.println ("Kesden");
                 break;
               
       default: System.out.println ("Invalid choice");
     }
  }
 }
  

In the code above, we use the return keyword by itself, without specifying anything to return. This tells Java to leave the method at that point, and since we're inside the main method, it means to simply end the program.