March 2003 Technical Tip An Introduction to Java Exceptions

Exceptions are a means of error trapping. Exceptions support structured programming by allowing the caller, rather than the called, to determine how an error condition should be handled. In the short space allowed here we will demonstrate (1) creating an exception class, (2) throwing the exception when an error condition has been detected within a method, and (3) coding try/catch blocks to handle the thrown exception. We will use a simple password example: the user keys in a password, and an exception is thrown if the password is invalid.

Coding an exception class is generally a trivial task. These classes usually follow the pattern shown here. Our exception extends java.lang.Exception, which accepts a String which will be displayed when an exception occurs.

public class PasswordException
    extends java.lang.Exception
{
    public PasswordException()
    {
        this("Invalid password.");
    }

    public PasswordException(String msg)
    {
        super(msg);
    }
}

We throw the exception when an error condition has been detected within a method. Note how the message to be passed to java.lang.Exception can be overridden.

public static void checkPassword(String password)
    throws PasswordException
{
    if (!password.equalsIgnoreCase("PASSWORD"))
        throw new PasswordException("Sorry, bad password.");
}

We code try/catch blocks whenever we invoke a method which may throw an exception. Note that in this way the ultimate decision as to how the error will be handled is left to the caller.

import java.io.*;
public class DemoPasswordException
{
    public static void main(String[] args)
        throws IOException
    {
        BufferedReader keyboard = new BufferedReader(
            new InputStreamReader(System.in));
        System.out.print("Enter password: ");
        String pw = keyboard.readLine();
        try
        {
            checkPassword(pw);
        }
        catch (PasswordException pe)
        {
            System.err.println(pe);
            System.exit(1);
        }
        System.out.println("You're in!");
    }

    public static void checkPassword(String password)
        throws PasswordException
    {
        if (!password.equalsIgnoreCase("PASSWORD"))
            throw new PasswordException("Sorry, bad password.");
    }
}

Failure to code try/catch blocks will cause a compile time error:

DemoPasswordException.java:12: unreported exception PasswordException; 
must be caught or declared to be thrown
        checkPassword(pw);
        ^
1 error

Sample execution follows:

C:\Java\Mine>java DemoPasswordException
Enter password: Bill
PasswordException: Sorry, bad password.

C:\Java\Mine>java DemoPasswordException
Enter password: password
You're in!

Note that exceptions which extend java.lang.RuntimeException (vs. Exception) work the same way, but coding of the try/catch blocks is optional.

Exceptions is just one of many features of the Java programming language which will be new to COBOL and PL/I programmers. We at Caliber Data Training are pleased to offer Java training in a number of environments, including IBM WebSphere Studio Application Developer. We are confident that your COBOL and PL/I programmers will benefit from learning Java from instructors who speak their language! We hope you will consider us when deciding upon a training provider!


Go to the articles index. Written by Bill Qualls. Copyright 2003 by Caliber Data Training 800.938.1222