Sams Teach Yourself C in 21 Days

(singke) #1
In Java, an error is referred to as an exception. When an error occurs, the program is
throwing an exception. Different errors cause different types of exceptions to be thrown.
Java defines a variety of exception classes corresponding to just about any error situation
you can imagine.
Java provides keywords specifically for working with exceptions. These are tryand
catch. In broad terms, Java error handling works like this:


  1. Use the trykeyword to identify blocks of code where particular exceptions are
    likely to occur.

  2. Use the catchkeyword to identify code that will be executed should an exception
    occur within a specific tryblock. A block of code identified with a catchkeyword
    is an exception handler. There will be a separate catchblock for each type of
    exception you expect.

  3. If an error occurs in a tryblock, an exception of the type corresponding to the
    error is thrown or generated.

  4. The exception generated in (3) is compared with the catchblocks following the
    tryblock. If a match is found, the code in that catchblock is executed.
    If an exception does not occur, the code in the catch blocks is not executed. The follow-
    ing shows an example of how try and catch statements are laid out:
    try {
    // Code that may generate an exception
    // is placed here.
    }
    catch (ExceptionType1e) {
    // Code to handle the error corresponding to
    // ExceptionType1 goes here.
    }
    catch (ExceptionType2e) {
    // Code to handle the error corresponding to
    // ExceptionType2 goes here.
    }
    Some classes that are part of Java are designed to throw exceptions, and code that uses
    these classes must use tryandcatchappropriately, or the Java compiler will not accept
    the code. You are given a warning when this happens, and you can correct the code as
    needed. A powerful feature of Java exceptions is that they can be thrown “up” the hierar-
    chy of methods. In other words, if method A calls method B, then method B can either
    deal with any exceptions it generates, or it can throw them “up” to method A for han-
    dling.


744 Bonus Day 6

41 448201x-Bonus6 8/13/02 11:23 AM Page 744

Free download pdf