CSC 224 Lecture Notes


Week 8: Exceptions and Javadoc



Questions on the homework or the quiz? [1/22]
Error handling [2/22]
What are exceptions? [3/22]
Why use "exception handling"? [4/22]
Under the hood [5/22]
Types of exceptions [6/22]
Creating new exception classes [7/22]
Throwing exceptions [8/22]
When to throw exceptions [9/22]
Exceptions and inheritance [10/22]
Catching exceptions [11/22]
When to catch exceptions [12/22]
Cleaning up with finally [13/22]
Quick example [14/22]
Some encountered exceptions [15/22]
Questions [16/22]
Answers [17/22]
Javadoc [18/22]
Commenting the java source codes [19/22]
Tags in javadoc [20/22]
Files generated by javadoc [21/22]
Exam Next Week [22/22]

Questions on the homework or the quiz? [1/22]



-Homework not due until next week, any questions thus far?

Let's take the quiz...

Error handling [2/22]



What are exceptions? [3/22]



Why use "exception handling"? [4/22]


Let's demonstrate the Java advantage over traditional error handling code...

Advantage 1: Separating Error Handling Code from "Regular" Code

pseudocode:
readFile {
    open the file;
    determine its size;
    allocate that much memory;
    read the file into memory;
    close the file;
}
At first glance this function seems simple enough, but it ignores all of these potential errors: Your function would end up looking something like this:
errorCodeType readFile {
    initialize errorCode = 0;
    open the file;
    if (theFileIsOpen) {
        determine the length of the file;
        if (gotTheFileLength) {
            allocate that much memory;
            if (gotEnoughMemory) {
                read the file into memory;
                if (readFailed) {
                    errorCode = -1;
                }
            } else {
                errorCode = -2;
            }
        } else {
            errorCode = -3;
        }
        close the file;
        if (theFileDidntClose && errorCode == 0) {
            errorCode = -4;
        } else {
            errorCode = errorCode and -4;
        }
    } else {
        errorCode = -5;
    }
    return errorCode;
}

versus the Java style:

readFile {
    try {
        open the file;
        determine its size;
        allocate that much memory;
        read the file into memory;
        close the file;
    } catch (fileOpenFailed) {
        doSomething;
    } catch (sizeDeterminationFailed) {
        doSomething;
    } catch (memoryAllocationFailed) {
        doSomething;
    } catch (readFailed) {
        doSomething;
    } catch (fileCloseFailed) {
        doSomething;
    }
}

Advantage 2: Propagating Errors Up the Call Stack

Old style:
method1 {
    call method2;
}
method2 {
    call method3;
}
method3 {
    call readFile;
}
Suppose that method1 is the only method interested in the errors that occur within readFile. Traditional error notification techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1
method1 {
    errorCodeType error;
    error = call method2;
    if (error)
        doErrorProcessing;
    else
        proceed;
}
errorCodeType method2 {
    errorCodeType error;
    error = call method3;
    if (error)
        return error;
    else
        proceed;
}
errorCodeType method3 {
    errorCodeType error;
    error = call readFile;
    if (error)
        return error;
    else
        proceed;
}
Java style:
method1 {
    try {
        call method2;
    } catch (exception) {
        doErrorProcessing;
    }
}
method2 throws exception {
    call method3;
}
method3 throws exception {
    call readFile;
}

Advantage 3: Grouping Error Types and Error Differentiation

-Exceptions are first-class objects in Java
-Allowing for better error handling depending on the specifications of the particular error, which can be very unique, and even more so if you define your own.
-For example, in the following diagram, ArrayException is a subclass of Exception (a subclass of Throwable) and has three subclasses.

-InvalidIndexException, ElementTypeException, and NoSuchElementException are all leaf classes. Each one represents a specific type of error that can occur when manipulating an array.
-You can have a catch statement for each one of them

Under the hood [5/22]


  1. A method throws an exception
  2. the runtime system leaps into action to find someone to handle the exception
  3. The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate exception handler.
  4. If the runtime system searches all of the methods on the call stack without finding an appropriate exception handler, the Java program terminates.

Types of exceptions [6/22]


See the graphic on page 638 of the text
... private class MyButtonListener implements ActionListener{ public void actionPerformed(ActionEvent event){ try{ if(event.getActionCommand().equals("int/0")){ int i = 10/(0); } else if(event.getActionCommand().equals("array bounds")){ a[0] = a[8]; } else if(event.getActionCommand().equals("bad cast")){ a = (double[])event.getSource(); } else if(event.getActionCommand().equals("null pointer")){ event = null; System.out.println(event.getSource()); } else if(event.getActionCommand().equals("no such file")){ java.io.FileInputStream f = new java.io.FileInputStream("no such file"); } }catch(Exception e){ tf.setText(""); tf.setText(e.getClass().getName()); } } } private TextField tf; private double a[] = new double[4]; ... Full code of ExceptionDemo.java

Creating new exception classes [7/22]



Throwing exceptions [8/22]



When to throw exceptions [9/22]


When writing a method and...

Exceptions and inheritance [10/22]



Catching exceptions [11/22]



When to catch exceptions [12/22]



Cleaning up with finally [13/22]



Quick example [14/22]


try
{ f = new FileReader("test");
System.out.println(f.read());
} catch (FileNotFoundException e)
{ System.err.println("Not found!"); }
catch (IOException e)
{ System.err.println("IO problem!"); }
finally
{ if (f!=null) f.close(); }

Some encountered exceptions [15/22]



Questions [16/22]


  1. Is the following code legal?
    try {
        ...
    } finally {
        ...
    }
    
  2. What exception types can be caught by the following handler?
    catch (Exception e) {
        ...
    }
    
    What is wrong with using this type of exception handler?

  3. What exceptions can be caught by the following handler?
    ...
    } catch (Exception e) {
        ...
    } catch (ArithmeticException a) {
        ...
    }
    
    Is there anything wrong with this exception handler as written? Will this code compile?

  4. What will be returned below?
    try {
        return 2;
    } finally {
        return 3;
    }
    

Answers [17/22]


  1. Question: Is the following code legal?
    try {
        ...
    } finally {
        ...
    }
    
    Answer: Yes, it's legal. A try statement does not have to have a catch statement if it has a finally statement. If the code in the try statement has multiple exit points and no associated catch clauses, the code in the finally statement is executed no matter how the try block is exited.

  2. Question: What exception types can be caught by the following handler?
    catch (Exception e) {
        ...
    }
    
    What is wrong with using this type of exception handler?

    Answer: This handler catches exceptions of type Exception; therefore, it catches any exception. This can be a poor implementation because you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, the runtime system is forced to determine the type of exception before it can decide on the best recovery strategy.

  3. Question: What exceptions can be caught by the following handler?
    ...
    } catch (Exception e) {
        ...
    } catch (ArithmeticException a) {
        ...
    }
    
    Is there anything wrong with this exception handler as written? Will this code compile?

    Answer: This first handler catches exceptions of type Exception; therefore, it catches any exception, including ArithmeticException. The second handler could never be reached. This code will not compile.

  4. Question: What will be returned below?
    try {
        return 2;
    } finally {
        return 3;
    }
    
    Answer: 3, the try will complete correctly, but before any value is actually returned, finally will run and its return statement will be returned.

Javadoc [18/22]



Commenting the java source codes [19/22]


/** * Javadoc looks like this, you can use <b>HTML</B> tags. */

Tags in javadoc [20/22]


full list for your reference:
@author  name-text
Creates an "Author" entry.  A doc comment may contain multiple @author tags.

@deprecated  deprecated-text
Adds a deprecated comment indicating that this API should not use the specified features of the class. Deprecated notes normally appear when a class has been enhanced with new and improved features, but older features are maintained for backwards compatibility.

@exception  class-name description
The @exception tag is a synonym for @throws.

{@link  name  label}
This tag allows the programmer to insert an explicit hyperlink to another HTML document.

@param  parameter-name description
Adds a parameter to the "Parameters" section. The description may be continued on the next line.

@return  description
Adds a "Returns" section, which contains the description of the return value.

@see  reference
Adds a "See Also" heading with a link or text entry that points to reference.

@serial  field-description
Used in the doc comment for a default serializable field.

An optional field-description augments the doc comment for the field. The combined description must explain the meaning of the field and list the acceptable values.

@serialData  data-description
A data-description documents the sequences and types of data, specifically the optional data written by the writeObject method and all data written by the Externalizable.writeExternal method. The @serialData tag can be used in the doc comment for the writeObject, readObject, writeExternal, and readExternal methods.

@serialField  field-name  field-type  field-description
Documents an ObjectStreamField component of a Serializable class' serialPersistentFields member. One @serialField tag should be used for each ObjectStreamField component.

@since  since-text
Adds a "Since" heading with the specified since-text to the generated documentation. These notes are used for new versions of a class to indicate when a feature was first introduced. For example, the Java API documentation uses this to indicate features that were introduced in Java 1.0, Java 1.1 or Java 2.

@throws  class-name  description
The @throws and @exception tags are synonyms. Adds a "Throws" subheading to the generated documentation, with the class-name and description text. The class-name is the name of the exception that may be thrown by the method. If this class is not fully-specified, javadoc uses the search order to look up this class.

@version  version-text
Adds a "Version" subheading with the specified version-text to the generated docs when the -version option is used. The text has no special internal structure. A doc comment may contain at most one @version tag. Version normally refers to the version of the software (such as the JDK) that contains this class or member.

Files generated by javadoc [21/22]


/** * A data model for an element. * @author Paul Gestwicki */ public class Element { /** * The name of an element. This is the element's full name, * such as oxygen or lithium. */ private String name; /** * The abbreviation for an element. This is the official abbreviation * as would appear in a periodic table. For example, the abbreviation * for Oxygen is O. */ private String abbreviation; /** * The atomic number of the element. This is the number of protons * contained in an atom's nucleus. */ private int atomicNumber; /** * Public element constructor. * @param name the name of the element * @param abbreviation the element's official abbreviation * @param number the element's atomic number */ public Element(String name, String abbreviation, int number) { this.name = name; this.abbreviation = abbreviation; this.atomicNumber = number; } /** * Get the element's abbreviation. * @return element abbreviation * @see #abbreviation */ public String getAbbreviation() { return abbreviation; } /** * Get the element's atomic number. * @return atomic number * @see #atomicNumber */ public int getAtomicNumber() { return atomicNumber; } /** * Get the name of the element as a string. * @return element's name * @see #name */ public String getName() { return name; } } /** * A table used to store and look up elements. * The periodic table organizes elements by their atomic numbers. * Internally, an array representation is used to allow for * speedy access. We are assuming that the number and order of * elements is not going to change. * @author Paul Gestwicki */ public class PeriodicTable { /** * The internal representation of the periodic table. * The array is indexed by atomic number. */ private Element[] table; /** * Construct a new periodic table. * @param numberOfElements the number of elements that can be * stored in the periodic table */ public PeriodicTable(int numberOfElements) { table = new Element[numberOfElements]; } /** * Add an element to the periodic table. * @param e the element to add */ public void addElement(Element e) { table[e.getAtomicNumber()] = e; } /** * Fetch an element from the table by its atomic number. * @param atomicNumber the atomic number of the element that * is being retrieved from the table. * @return the element with the given atomic number, or null if it * has not been added yet (see {@link #addElement(Element)}). */ public Element getElement(int atomicNumber) { return table[atomicNumber]; } } /** * An aggregation of elements forms a molecule. * We consider neither the types of bonds nor the arrangement * of the molecule's elements; this class is only used to * store the types of elements that comprise a molecule. * @author Paul Gestwicki */ public class Molecule { /** * The elements that make up a molecule. * This member must be initialized in all constructors. */ private Element[] elements; /** * Construct a new molecule from the given elements. * @param elements an array of elements that make up this * molecule. */ Molecule(Element[] elements) { this.elements = new Element[elements.length]; System.arraycopy(elements, 0, this.elements, 0, elements.length); } } Element.java
PeriodicTable.java
Molecule.java
The Result

Exam Next Week [22/22]


-Exam 8 Next Week
-Homework 8 Due Before Class... only a freestyle this week. Enjoy the weekend :0)