Table of ContentsAdvanced Object-Oriented ProgrammingPackages, Import, and CLASSPATH

Exceptions

Exceptions are objects that contain information about an event occurring outside of normal conditionsusually an error of some type. Typically you write code to throw an exception when this type of situation occurs. The exception then propagates back through the call stack (the previous methods) until it is caught in your code. You can think of an exception as something like an object containing an error report.

An exception can be a full class object, so it can have any elements you need to deal with the exceptional case when it occurs, such as any reason for the error. To create your own exception, you must extend the Exception class. To catch an exception, you must first wrap the code that might generate the exception in a try block. You can then use the catch keyword, followed by the exception class you want to catch. Here's an example of an exception being thrown and subsequently caught:

public void setColor(int r, int g, int b)
{
    try
    {
        if (r > 255 || g > 255 || b > 255)
            throw new Exception("Invalid color");

        setColor(r, g, b);
    }

    catch(Exception e)
    {
        setColor(0, 0, 0);
    }
}

Sometimes you will encounter cases in which an exception might circumvent code you absolutely have to execute, such as code to release resources or carry out critical cleanup operations. The finally clause, which can follow any try block, is the place for this code. For example:

public void setColor(int ar, int ag, int ab)
{
    int r = ar;
    int g = ag;
    int b = ab;

    try
    {
        if (r > 255 || g > 255 || b > 255)
            throw new Exception("Invalid color");
    }

    catch(Exception e)
    {
        System.out.println("fixing up bad color values");
        r = g = b = 0;
    }

    finally
    {
        setColor(r, g, b);
    }
}

If you don't want to handle an exception, you can declare your method so it throws the exception on the call stack (to the caller of the method and so on until it is handled). For example:

public void setColor(int ar, int ag, int ab) throws Exception
{
    int r = ar;
    int g = ag;
    int b = ab;

    try
    {
        if (r > 255 || g > 255 || b > 255)
            throw new Exception("Invalid color");
    }

    finally
    {
        setColor(r, g, b);
    }
}

In this case, the finally code is still executed, but the exception is passed back up to be handled by the method's caller as it sees fit.

    Table of ContentsAdvanced Object-Oriented ProgrammingPackages, Import, and CLASSPATH