The Artima Developer Community
Sponsored Link

Exceptions in Java
Exceptions in the Java Language and Virtual Machine
by Bill Venners
First Published in JavaWorld, June 1998

<<  Page 2 of 9  >>

Advertisement

Throwing exceptions
To throw an exception, you simply use the throw keyword with an object reference, as in:

throw new TooColdException();

The type of the reference must be Throwable or one of its subclasses.

The following code shows how a class that represents the customer, class VirtualPerson, might throw exceptions if the coffee didn't meet the customer's temperature preferences. Note that Java also has a throws keyword in addition to the throw keyword. Only throw can be used to throw an exception. The meaning of throws will be explained later in this article.

// In Source Packet in file except/ex1/VirtualPerson.java
class VirtualPerson {

    private static final int tooCold = 65;
    private static final int tooHot = 85;

    public void drinkCoffee(CoffeeCup cup) throws
        TooColdException, TooHotException {

        int temperature = cup.getTemperature();
        if (temperature <= tooCold) {
            throw new TooColdException();
        }
        else if (temperature >= tooHot) {
            throw new TooHotException();
        }
        //...
    }
    //...
}

// In Source Packet in file except/ex1/CoffeeCup.java
class CoffeeCup {
    // 75 degrees Celsius: the best temperature for coffee
    private int temperature = 75;
    public void setTemperature(int val) {
        temperature = val;
    }
    public int getTemperature() {
        return temperature;
    }
    //...
}

<<  Page 2 of 9  >>


Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2014 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us