Java Exceptions  «Prev  Next»
Lesson 2The Purpose of Java Exceptions
ObjectiveState the purpose of exceptions.

State the Purpose of Java Exceptions

Java Exceptions provide a formal way of handling error conditions that might arise in your software or in software that you are using. In addition to responding to an exception, you can also signal (or throw) your own exception, as you will learn about shortly.

Three Advantages of Java Exceptions

  1. Allows for the creation of new exceptions that are custom to a particular application domain.
  2. It improves code because error handling code is clearly separated from the main program logic.
  3. Java's exception mechanism improves the code because it does not have to include error handling code if it is not capable of handling it.

Advice regarding Exceptions

Exceptions often provide information concerning why they were triggered, because Exception is a subclass of Throwable. Throwable defines a method called getMessage(), which returns a String describing what went wrong. One way to assist with debugging is to write this message to the standard output or the standard error in the exception handler, as in
  1. System.out.println(e.getMessage()), or
  2. System.err.println(e.getMessage()).

Why use exceptions?

Exceptions came about to solve a sticky problem with error handling that has existed since the beginning of programming. It has to do with at least two factors:
  1. The difficulty of separating error reporting and error handling
  2. The difficult-to-read programs which result from mixing code that runs when everything goes as expected with code that runs only when the unexpected occurs (sometimes error-handling code is trickier than the code that runs when everything goes right)

A perfect example involves data conversion. We can create an instance of a wrapper class, such as Integer, by supplying it with a String as a parameter to its constructor, as in:

Integer myIntWrapper = new Integer(s);

Notice that there is no result value indicating whether the constructor was successful in creating the new instance. So what happens when s does not contain a valid number?
Without exceptions, there are at least three possibilities:
  1. The constructor could not create a new instance and instead returned null.
  2. The constructor could create a new instance anyway, but initialized to some default value, such as zero (0).
  3. The constructor could try to determine what number the invalid text might represent and work with its best guess.
Next let's discuss how Java separates error detection and error handling.