Exceptions in
Java - JavaWorld - July
1998
Tutorial Details:
Exceptions in Java
Exceptions in Java
By: By Bill Venners
The full story of exceptions in the Java language and virtual machine
xceptions are the customary way in Java to indicate to a calling method that an abnormal condition has occurred. This article is a companion piece to this month's Design Techniques installment, which discusses how to use exceptions appropriately in your programs and designs. Look to this companion article for a tutorial on the nuts and bolts of what exceptions are and how they work in the Java language and virtual machine.
When a method encounters an abnormal condition (an exception condition ) that it can't handle itself, it may throw an exception. Throwing an exception is like throwing a beeping, flashing red ball to indicate there is a problem that can't be handled where it occurred. Somewhere, you hope, this ball will be caught and the problem will be dealt with. Exceptions are caught by handlers positioned along the thread's method invocation stack. If the calling method isn't prepared to catch the exception, it throws the exception up to its calling method, and so on. If one of the threads of your program throws an exception that isn't caught by any method along the method invocation stack, that thread will expire. When you program in Java, you must position catchers (the exception handlers) strategically, so your program will catch and handle all exceptions from which you want your program to recover.
Exception classes
In Java, exceptions are objects. When you throw an exception, you throw an object. You can't throw just any object as an exception, however -- only those objects whose classes descend from Throwable . Throwable serves as the base class for an entire family of classes, declared in java.lang , that your program can instantiate and throw. A small part of this family is shown in Figure 1.
As you can see in Figure 1, Throwable has two direct subclasses, Exception and Error . Exceptions (members of the Exception family) are thrown to signal abnormal conditions that can often be handled by some catcher, though it's possible they may not be caught and therefore could result in a dead thread. Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError , that may not be so easy to handle. In general, code you write should throw only exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the Java virtual machine itself.
Figure 1. A partial view of the Throwable family
In addition to throwing objects whose classes are declared in java.lang , you can throw objects of your own design. To create your own class of throwable objects, you need only declare it as a subclass of some member of the Throwable family. In general, however, the throwable classes you define should extend class Exception . They should be "exceptions." The reasoning behind this rule will be explained later in this article.
Whether you use an existing exception class from java.lang or create one of your own depends upon the situation. In some cases, a class from java.lang will do just fine. For example, if one of your methods is invoked with an invalid argument, you could throw IllegalArgumentException , a subclass of RuntimeException in java.lang .
Other times, however, you will want to convey more information about the abnormal condition than a class from java.lang will allow. Usually, the class of the exception object itself indicates the type of abnormal condition that was encountered. For example, if a thrown exception object has class IllegalArgumentException , that indicates someone passed an illegal argument to a method. Sometimes you will want to indicate that a method encountered an abnormal condition that isn't represented by a class in the Throwable family of java.lang .
As an example, imagine you are writing a Java program that simulates a customer of a virtual café drinking a cup of coffee. Consider the exceptional conditions that might occur while the customer sips. The class hierarchy of exceptions shown in Figure 2 represents a few possibilities.
Figure 2. Exception hierarchy for coffee sipping
If the customer discovers, with dismay, that the coffee is cold, your program could throw a TooColdException . On the other hand, if the customer discovers that the coffee is overly hot, your program could throw a TooHotException . These conditions could be exceptions because they are (hopefully) not the normal situation in your café. (Exceptional conditions are not necessarily rare, just outside the normal flow of events.) The code for your new exception classes might look like this:
// In Source Packet in file except/ex1/TemperatureException.java
class TemperatureException extends Exception {
}
// In Source Packet in file except/ex1/TooColdException.java
class TooColdException extends TemperatureException {
}
// In Source Packet in file except/ex1/TooHotException.java
class TooHotException extends TemperatureException {
}
This family of classes, the TemperatureException family, declares three new types of exceptions for your program to throw. Note that each exception indicates by its class the kind of abnormal condition that would cause it to be thrown: TemperatureException indicates some kind of problem with temperature; TooColdException indicates something was too cold; and TooHotException indicates something was too hot. Note also that TemperatureException extends Exception -- not Throwable , Error , or any other class declared in java.lang .
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;
}
//...
}
Catching exceptions
To catch an exception in Java, you write a try block with one or more catch clauses. Each catch clause specifies one exception type that it is prepared to handle. The try block places a fence around a bit of code that is under the watchful eye of the associated catchers. If the bit of code delimited by the try block throws an exception, the associated catch clauses will be examined by the Java virtual machine. If the virtual machine finds a catch clause that is prepared to handle the thrown exception, the program continues execution starting with the first statement of that catch clause.
As an example, consider a program that requires one argument on the command line, a string that can be parsed into an integer. When you have a String and want an int , you can invoke the parseInt() method of the Integer class. If the string you pass represents an integer, parseInt() will return the value. If the string doesn't represent an integer, parseInt() throws NumberFormatException . Here is how you might parse an int from a command-line argument:
// In Source Packet in file except/ex1/Example1.java
class Example1 {
public static void main(String[] args) {
int temperature = 0;
if (args.length > 0) {
try {
temperature = Integer.parseInt(args[0]);
}
catch(NumberFormatException e) {
System.out.println(
"Must enter integer as first argument.");
return;
}
}
else {
System.out.println(
"Must enter temperature as first argument.");
return;
}
// Create a new coffee cup and set the temperature of
// its coffee.
CoffeeCup cup = new CoffeeCup();
cup.setTemperature(temperature);
// Create and serve a virtual customer.
VirtualPerson cust = new VirtualPerson();
VirtualCafe.serveCustomer(cust, cup);
}
}
Here, the invocation of parseInt() sits inside a try block. Attached to the try block is a catch clause that catches NumberFormatException :
catch(NumberFormatException e) {
System.out.println(
"Must enter integer as first argument.");
return;
}
The lowercase character e is a reference to the thrown (and caught) NumberFormatException object. This reference could have been used inside the catch clause, although in this case it isn't. (Examples of catch clauses that use the reference are shown later in this article.)
If the user types Harumph as the first argument to the Example1 program, parseInt() will throw a NumberFormatException exception and the catch clause will catch it. The program will print:
Must enter integer as first argument.
Although the above example had only one catch clause, you can have many catch clauses associated with a single try block. Here's an example:
// In Source Packet in file except/ex1/VirtualCafe.java
class VirtualCafe {
public static void serveCustomer(VirtualPerson cust,
CoffeeCup cup) {
try {
cust.drinkCoffee(cup);
System.out.println("Coffee is just right.");
}
catch (TooColdException e) {
System.out.println("Coffee is too cold.");
// Deal with an irate customer...
}
catch (TooHotException e) {
System.out.println("Coffee is too hot.");
// Deal with an irate customer...
}
}
}
If any code inside
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Exceptions in
Java - JavaWorld - July
1998
View Tutorial: Exceptions in
Java - JavaWorld - July
1998
Related
Tutorials:
How to write
a Java Card applet: A developer's
guide
How to write
a Java Card applet: A developer's
guide |
Enhance your Java application with Java Native Interface (JNI)
Enhance your Java application with Java Native Interface (JNI) |
Cut down on
logging errors with Jylog
Cut down on
logging errors with Jylog |
J2SE 1.4
premieres Java's
assertion capabilities, Part 2
J2SE 1.4
premieres Java's
assertion capabilities, Part 2 |
Integrate EJBs with CORBA
Integrate EJBs with CORBA |
Exceptions: Don't
get thrown for a loss
Exceptions: Don't
get thrown for a loss |
J2SE 1.4
breathes new life into the CORBA community, Part
1
J2SE 1.4
breathes new life into the CORBA community, Part
1 |
Beware the dangers of
generic Exceptions
Beware the dangers of
generic Exceptions |
Java Development on Eclipse, Part 2
Java Development on Eclipse, Part 2
Editor's note: In part one of this two-part series of excerpts from Eclipse, author Steve Holzner provided examples of how Eclipse makes it easier to create Java code from scratch. Continuing in that vein, in this we |
Software Download Central
compatible.
GNU getopt - Java port
A while back I found myself in need of a Java command line option parser. Unsatisfied with free versions I was able to find on the net, I volunteered to port the GNU getopt family of functions from C to Java. The current release |
Java theory and practice: Kill bugs dead
Inspection tools like FindBugs provide a second layer of defense against common coding errors. |
Attribute-Oriented Programming with Java 1.5, Part 2
Peeking Inside the Box: Attribute-Oriented Programming with Java 1.5,Part
In the previous article in this series, "Peeking Inside the Box, Part 1," I introduced the concepts of Attribute-Oriented Programming, Java 1.5 annotations, and bytecode instrume |
Java Resources
There are all Java freebies. Some of these are old, and not under maintenance. Download and use them at your risk. In case of queries, mail subrahmanyam_avb@technologist.com or varalakshmi_a@techie.com. |
UML 2.0 Sequence Diagramming
Modeling Complex Code in SunONE Studio with Embarcadero's Integrated Modeling Developement Environment, Describe. |
What package names are defined in the J2ME environment?
A compendium of J2ME package names, neatly arranged by JSR and presented for your illumination. |
Struts, JavaServer Faces, and Java Studio Creator:
The Evolution of Web Application Frameworks Sun Microsystems' Craig McClanahan, the creator of the Apache Struts Framework, co-specification lead for JavaServer Faces 1.0, and prime architect for Sun Java Studio Creator's new release, explains all three. |
Interoperability with Patterns and Strategies for Document-Based Web Services
In Part 2 of this article, we demonstrate interoperability for document-driven web services with Microsoft .NET (C#) using strategies discussed in Part 1. |
Core Java Interview Questions!
Core Java Interview Questions!
Core Java Interview Questions
Question: What is transient variable?
Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written |
Introduction to JSP tags JSP Directives
Introduction to JSP tags JSP Directives
INTRODUCTION TO JSP TAGS
I n this lesson we will learn about the various tags available in JSP with suitable examples. In JSP tags can be devided into 4 different types. These are:
Directives
In the |
one-jar
One-JAR is a simple solution to a vexing problem in Java: how to distribute an application as a single jar-file, when it depends on multiple other jar-files. One-JAR uses a custom classloader to discover library jar files inside the main jar. |
|
|
|