tailieunhanh - Essential ActionScript 3.0 PHẦN 4

public function VirtualPetInsufficientDataException ( ) { super("Pet name too short."); } } } // Code in : package zoo { public class VirtualPetExcessDataException extends VirtualPetNameException { public function VirtualPetExcessDataException ( ) { super("Pet name too long."); } } } Each class specifies the value of its message variable directly and does not allow it to be customized on a per-use basis. When catching any of the preceding VirtualPet exceptions, our program will use the exception’s datatype (not the message variable) to distinguish between the three kinds of exceptions. Now that we have three exception types, let’s update our setName( ) method. | public function VirtualPetInsufficientDataException super Pet name too short. _ _ Code in package zoo public class VirtualPetExcessDataException extends VirtualPetNameException public function VirtualPetExcessDataException super Pet name too long. _ _ Each class specifies the value of its message variable directly and does not allow it to be customized on a per-use basis. When catching any of the preceding VirtualPet exceptions our program will use the exception s datatype not the message variable to distinguish between the three kinds of exceptions. Now that we have three exception types let s update our setName method to throw those types. Here s the code public function setName newName String void if 0 throw new VirtualPetNameException else if newName throw new VirtualPetInsufficientDataException else if throw new VirtualPetExcessDataException petName newName Notice that we do not pass any error description to the various VirtualPet exception constructors. Once again the description of each exception is set by each custom Error subclass using its message variable. With each VirtualPet exception represented by its own class the errors that can be generated by the setName method are well-known to programmers working with VirtualPet instances. The exception types are visible outside the VirtualPet class exposed appropriately to programmers working on the application. Just by glancing at the application class hierarchy the programmer can determine the exceptions that relate to the VirtualPet class. Furthermore if the programmer mistakenly uses the wrong name for an exception the compiler generates a datatype error. Now let s see how to add branching logic to our code based on the types of exceptions that can be generated by setName . Pay close attention to the datatype of each catch block parameter and the placement of each catch block. Handling Multiple Types of Exceptions 251

TỪ KHÓA LIÊN QUAN