CS 120 Lab 11
Basic exceptions and try-catch blocks
Tom Linton, http://www.cs.moravian.edu/~linton
Moravian College, Spring 1999

Work alone on this lab.


Java signals that errors, or exceptionally rare events have occured by throwing exceptions. Exceptions are thrown, they do not occur on their own, and this makes it absolutely clear that something is wrong whenever an exception is thrown. The use of exceptions is a powerful way to handle "odd occurences" or exceptional events. Many times, you can write code which works for all reasonable input values, but a small number of exceptional input values would cause problems. It is expensive (in terms of running time) to always check for these rare input values, and often times these safety checks lower the readability of your code. Suppose you had a method,
delete(String currentString),
included in a basic word processing program. The method is suppose to delete a substring of some current string (and return the resulting string, after the deletion has been done), so code (in a class extending the SimpleGUI class) for this method, which nearly always works would be:
public String delete(String currentString) {
   String result;
   displayResult("Your current text is: " + currentString);
   String deleteString = getString("What substring would you like to delete?");
   int startIndex = currentString.indexOf(deleteString);
   result = currentString.substring(0, startIndex) +
      currentString.substring(startIndex + deleteString.length() );
   return result;
}
However, if the user enters a string to delete which is longer than the current string, or not a substring of the current string, the line defining the value of the variable result will throw a StringIndexOutOfBoundsException, which means roughly that your code is asking for a part of a string variable which doesn't exist. If you look at the Java documentation on the substring method of the String class, you'll see that substring "throws StringIndexOutOfBoundsException". The most common problems with the code above, occur when startIndex = -1 (signaling that the entered substring to delete is NOT actually a substring of the current text). One reasonable way to avoid the exception being thrown is to add an if-statement which tests for this:
 
public String delete(String currentString) {
   String result;
   displayResult("Your current text is: " + currentString);
   String deleteString = getString("What substring would you like to delete?");
   int startIndex = currentString.indexOf(deleteString);
   if (startIndex >= 0)
      result = currentString.substring(0, startIndex) +
        currentString.substring(startIndex + deleteString.length() );
   else {
      displayResult("String not found-no deletion performed");
      result = currentString;
   }
   return result;
}
The code above works fine and is much better than the original code, but it checks a condition which we hope is always true (each and every time we call this method) and it causes an unnatural look to the method. Another alternative is a try-catch block:
 
public String delete(String currentString) {
   String result;
   displayResult("Your current text is: " + currentString);
   String deleteString = getString("What substring would you like to delete?");
   try {
      int startIndex = currentString.indexOf(deleteString);
      result = currentString.substring(0, startIndex) +
        currentString.substring(startIndex + deleteString.length() );
   }
   catch (StringIndexOutOfBoundsException e) {
      displayResult("String not found-no deletion performed");
      result = currentString;
   }
   return result;
}
This ladder version retains much of the natural look of the original code, avoids the test for the rare condition
"startIndex == -1"
and makes it more clear what went wrong (the type of the exception being caught suggests a String index was out of bounds).

Assignment:

Do programming project 1 on page 236 of the text. That is, rewrite the delete, insert, replace and search methods of the EditableString class, using try-catch blocks. The text rewrites the delete method on page 235 and the course home page contains a link to the texts version of the EditableString and doEditOperation classes (follow the "source code" for Koffman text link near the top of the page). Submit only your new EditableString.java file, do NOT use the delete method code above (it has the wrong return type), and do NOT change the names (or types) of any of these methods. I will test your code using the doEditOperation.java file.