CS 051 Fall 2011

Lecture 32

Link Finder Example

We looked at another program that manipulates Strings. The class example FindLinks
reads in a web page, and extracts all of the link tags from it.

We further modified the while loop in the findLinks method so that only
the url's from the links were saved:

   while (tagPos >= 0) {
     int urlStart, urlEnd;

     tagEnd = fullpage.indexOf(">", tagPos + 1);

     urlStart = fullpage.indexOf("href=\"", tagPos) + "href=\"".length();
     urlEnd = fullpage.indexOf("\"", urlStart);

     //tag = fullpage.substring(tagPos, tagEnd + 1);
     tag = fullpage.substring(urlStart, urlEnd);
     links = links + tag + "\n";

     tagPos = lowerpage.indexOf("<a ", tagEnd);
   }

Exceptions

We have seen several Exceptions in class already:

     NullPointerException
     ArrayIndexOutOfBoundsException
     NumberFormatException

Exceptions give the programmer flexibility in handling cases where things go wrong.

The class example FragileColorMixer may throw an Exception
in two different cases. First, trying to create a color with a red, green, or blue value
outside the range 0-255 causes an IllegalArgumentException to be thrown. Also,
passing a String to parseInt that cannot be converted to an integer
(such as "a") will cause a NumberFormatException to be thrown.

We looked at two class examples, ColorMixer and SaferColorMixer, that solved
each of these problems by preventing the Exception from being thrown.

However, there is a more clever way to do this. We can use a try-catch block, and
handle the Exception after it is thrown.

try-catch blocks take the following form:

   try {
     some statements
   } catch {
     some other statements
   }

The "some other statements" are only executed if an Exception is thrown. This is
very handy, because it allows us to handle the Exception at the point in the code
where we know how.

In our examples above, parseInt cannot convert a String that does not
represent an Integer. Howver, parseInt doesn't know how serious the error is.
It doesn't know if it should end the program, or just ask for another string.
In the ColorMixer program, however, we know that the error was just bad user input.
We can ignore the first attempt, and ask the user for another value.

The class example ColorMixer with Warning Label shows how
we can use the exception to give the user a warning, and ask for another input.