O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Handling Multiple Types of Exceptions

The exception example from the preceding section was simplistic. What happens if our method generates more than one kind of error? Are they all sent to the same catch block? Well, that's up to the developer; they certainly could be, but it's more typical and better practice for different kinds of errors to be handled by separate catch blocks. Let's examine why.

Suppose we want a finer-grained set of error messages in our setName( ) method: one for general invalid data, one for a name that's too short, and one for a name that's too long. The body of our revised setName( ) method might look like this:

if (newName.indexOf(" ") == 0) {
  // Names can't start with a space...
  throw new Error("Invalid pet name specified.");
} else if (newName == "") {
  throw new Error("Pet name too short.");
} else if (newName.length > VirtualPet.maxNameLength) {
  throw new Error("Pet name too long.");
}

To handle the three possible error messages in our new setName( ) message, we might be tempted to code our try/catch/finally statement as follows:

try {
  somePet.setName("somePetName"); // If we get this far, no exception occurred; proceed as planned. trace("Pet name set successfully."); } catch (e:Error) { switch (e.message) { case "Invalid pet name specified.": trace("An error occurred: " + e.message); trace("Please specify a valid name."); break; case "Pet name too short.": trace("An error occurred: " + e.message); trace("Please specify a longer name."); break; case "Pet ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required