New to Java

New to Java Programming Center

New to Java

Programming Center

Java Platform Overview | Getting Started | Learning Paths
References & Resources | Certification | Supplements




Contents
Getting Started | NEXT>>Handling Exceptions

More on Exception Handling


Handling Errors with Exceptions

Exceptions and How to Handle Them

Using Exceptions

Class Throwable

In Part 1, you created the DiveLog class with a constructor that builds the frame for the Dive Log application, a JMenu, and initializes a JTabbedPane object with six titled tabs. Each tab creates an object from a placeholder class. In Part 2, you designed the Welcome class, which appears on the Welcome pane. In Part 3, the Diver.java class introduced encapsulation, illustrates how to collect user data and display the input on screen through the use event handling basics.

Part 4 reinforces these concepts, introduces the Log Dives pane, and shows you how to:

  • Prepare for and handle errors.
  • Read from and write to files (Java I/O).
  • Use the Box layout.
  • Use the JFileChooser class for naming new files.
  • Use the JOptionPane class to create pop-up boxes that print warnings or provide information.

 

Getting Started



For this part of the tutorial, you need one image and the Dives.java placeholder class that creates the Log Dives pane. You can use a different image other than the one provided here, but to prevent problems with layout, make the image the same size as the image provided.


  1. Save the following image to the divelog/images directory: gwhite.gif
    Image size: 299 by 970 pixels.
Or create an image of your own, but use the same pixel size as the one listed above.


Note: It's assumed you installed the Java TM 2 Platform, Standard Edition (J2SE TM ) on your system, and that you have completed Part 1, Part 2, and Part 3 of the Building an Application tutorial.

The Log Dives pane consists of multiple classes:

  • Dives.java
    Creates the main panel, which uses the border layout manager and initializes three other classes:
    • NorthPanel.java
      Reads a file into a text area. This class is added to the northern region of the Dives.java border layout.
    • CenterPanel.java
      Creates a text area with scroll bars in the central region of Dives.java border layout. The Save button creates a JFileChooser dialog box and writes the data to a file that the user specifically names.
    • WestPanel.java
      Initializes several additional classes that create the GUI for this panel, build a dive object, and save the object and reads the object from a file.

For now, create placeholder classes for the last three classes listed above.


  1. In your text editor, create three files, each saved with the following names and code content:
    • NorthPanel.java
    • package divelog;
      import java.awt.*;
      import javax.swing.*;
      public class NorthPanel extends JPanel
      { // Opens class
      
      } // Closes class
      
    • CenterPanel.java
    • package divelog;
      import java.awt.*;
      import javax.swing.*;
      public class CenterPanel extends JPanel
      { // Opens class
      } // Closes class
      
    • WestPanel.java
    • package divelog;
      import java.awt.*;
      import javax.swing.*;
      public class WestPanel extends JPanel
      { // Opens class
      } // Closes class
      
  2. Save each class
  3. Compile each class, using:
  4. javac NorthPanel.java
    javac WestPanel.java
    javac CenterPanel
    

Currently, each placeholder class does not have a constructor. Later in the tutorial, you define a constructor for each class.

Next, initialize the placeholder classes within the Dives.java class constructor.


  1. Open Dives.java in your text editor, initialize the classes you created, then add their identifiers to the border layout:
  2. public class Dives extends JPanel
    { // Opens class
                            public Dives() {// Opens constructor // Sets the layout for the page and the // background to white. setLayout(new BorderLayout()); setBackground(Color.white);  // Initializes the placeholder classes. NorthPanel northPanel = new NorthPanel(); CenterPanel centerPanel = new CenterPanel(); WestPanel westPanel = new WestPanel();  // Adds class objects to panel regions. add("North", northPanel); add("West", westPanel); add("Center", centerPanel); } // Closes constructor
    }// Closes class
                        
  3. Save the file.

Creating a class to initialize other objects demonstrates one way to organize a complex panel. This is especially useful if you need to use several different layouts. You could create one huge class for all of that, but by breaking down a panel into several classes you can make changes to individual sections without affecting the code in the others.

The Log Dives panel is organized with the following classes that teach Java I/O specifics:

  • NorthPanel: demonstrates how to read from a file
  • CenterPanel: demonstrates how to write to a file
  • WestPanel: demonstrates how to read and write objects to a file

The process of reading from and writing to files is error prone. The application might try to open a file that doesn't exist, or attempt to write to a file that is read-only. Any number of things can go wrong.

Before learning to read from and write to files, you need to understand how to prepare for and handle errors and problems that may occur.

Preparing for Problems

When an application encounters an error or unexpected condition, it sometimes terminates, displaying a message on the console. In some cases, the application doesn't start.

For instance, if you typed the following at the command line:

javac DisplayError.java

You'd get this error message, assuming you don't have a file called DisplayError.java:

javac DisplayError.java
error: cannot read: DisplayError.java
1 error

The compiler couldn't find the named file and printed this message to the screen. These types of console messages aren't always helpful, and often you don't want the application to terminate, but continue onto another bit of code you've written. To force an application to do something in the event of a problem, you must first catch and handle the problem condition. The Java programming language has special classes and syntax to deal with potential errors and problems.

Applications can generate many types of unexpected conditions. For instance, you may want the user to enter an int, but instead the user enters a String. The user may request the name of a file that does not exist, or your program logic may erroneously try to divide by zero. Unexpected conditions in an application are referred to as exceptions in the Java programming language. In other words, an exception is a way to indicate an abnormal condition in an application.

The steps for handling those exceptions are as follows:

  1. Your application tries a block of code, and an unexpected condition or error occurs
  2. Program control is transferred, or thrown, to a specific section of code
  3. That specific block of code catches and handles the problem

There are two types of conditions:

  • Errors
  • Exceptions

Errors indicate fatal errors, such as a system out of memory error. These are difficult to recover from. An error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

On the other hand, exceptions indicate non-fatal conditions that you can frequently catch and handle.

Exceptions and errors are objects. The classes used to create the objects are subclasses of the Throwable class. You don't use Throwable directly, but instead use one of its subclasses, such as Exception.

An Exception object is created by the code at the point where the error or condition occurred. This object holds information necessary to describe the condition. The Exception object is passed to the handling block of code, where you write instruction for what you want to happen in the event this error or condition should occur.

For instance, suppose you created a form for the user to fill in. You request that the user type the name of a file to read. Since you know it's possible that file may not exist on the user's system, you need to write code that catches and handles this condition. When the user types in the name of a nonexistent file, instead of the program terminating, you write code that pops up a box, letting the user know that file does not exist and ask if it should be created. Then you need to write code to handle a Yes or No response. Or perhaps you want to create a warning of some sort. At any rate, you've prepared for a possible condition and written code to handle it.

More specific exception classes are derived from the Exception and Error classes. Class Throwable and its subclasses have two constructors, one that takes no arguments and one that takes a String argument that can be used to produce an error message.

To prepare for possible conditions, where should you write the code to open a file for reading?

 

   A. In a catch clause
   B. In the main method
   C. In its own class
   D. In a try clause