Chapter 11: Exceptions

Version 2.31

Handouts:

11.1 Exception Handling

Exceptions are objects that represent errors or simply unusual events. Examples of kinds of exceptions.

Options for dealing with exceptions:

  1. Not handle it;
  2. Handle it where it occurs;
  3. Handle it elsewhere.

11.2 Uncaught Exceptions

An exception which is not handled (not caught) results in terminating the program, with a printout of the nature of the exception that occurred and the call stack trace showing where it occurred.

Listing 11.1 Zero: creates an exception by dividing by zero and does not catch it.

11.3 The try-catch Statement

This statement may be used to handle an exception where it occurs.

Syntax:

try {
  <statements>
}
catch (<exceptionType> <exceptionVar>) {
  <statements>
}
catch ...
finally {
  <statements>
}

The statements in the try block are attempted. There may be zero or more catch clauses; each one is an exception handler for a specific type of exception. If an exception occurs and there is a catch clause that matches that type of exception, the statements in the first such catch clause are executed. Regardless of whether an exception occurred and was caught, the statements in the finally block are executed. After any exception is caught and handled and the try block executed, control resumes in the next statement in the usual way.

The finally clause is optional; it may be used to release resources or simply to guarantee that certain statements are executed.

Listing 11.2 ProductCodes illustrates catching exceptions.

11.4 Exception Propagation

If an exception is not caught in the method where it occurs, it is passed up through the call stack until it is caught, or until it is thrown out of main, terminating the program.

Listings 11.3-11.4 Propagation/ExceptionScope illustrate catching an exception in a "higher up" method.

11.5 The Exception Class Hierarchy

See Figure 11.1, p. 549. The principle classes are Error and Exception, and their superclass is Throwable.

Exceptions can be explicitly instantiated and thrown when an error or unusual condition is detected in user code.

We can define our own subclasses of exception; often the subclass is very simple and serves merely as an exception type to be looked for in catch clauses.

public class MyException extends Exception { ... }

throw new MyException(...);

Error, RunTimeException, and their descendants are unchecked exceptions and need not be declared if they are not caught.

All other Exceptions are checked exceptions, and must be either explicitly caught, or the methods where they are not caught must declare that they throw these exceptions.

Listings 11.5-11.6 CreatingExceptions/OutOfRangeException illustrate subclassing, instantiating, throwing, and not catching exceptions.


BREAK


Review

...

11.6 I/O Exceptions

A lot of exceptions can occur in I/O, e.g., files not found or not readable or writable.

A stream is a sequence of data. The data flow from a source to a sink (destination).

There are three standard I/O streams:

These are normally connected to the keyboard and display devices, but may be redirected using the facilities of the operating system.

Unix I/O redirection and piping [ADDITION]

(Not in the textbook)

Examples: using echo, ls, cat, less, read v, etc., or (better?) using Redirectable.java:

java Redirectable < data.txt
java Redirectable > out
java Redirectable 2> err
java Redirectable &> errout
java Redirectable < data.txt > out 2> /dev/null

Etc.

Also try reading from /dev/random or /dev/urandom.

Java streams

Think of rivers of data, or think of plumbing carrying water through a house.

Java streams carry data; they are classified as sources (e.g., input files) or sinks (e.g., output files) of data, or filters that transform the data carried by other streams.

Files are opened with new FileReader(filename) or new FileWriter(filename).

Files should be closed (with the close method) when we are done with them. This releases resources, and makes sure all output is physically written out to disk.

Listing 11.7 TestData writes a file of test data.

Example

Develop a program to read a file of numbers and output their squares:

  1. Using stdin, stdout, with redirection: FileIO1.java
  2. Using files: FileIO2.java
  3. Using files (more compact notation): FileIO3.java

Useful patterns:

Scanner fileIn =
  new Scanner(new FileReader(newBufferedReader(INFILENAME);
PrintWriter fileOut =
  new PrintWriter(newBufferedWriter(new FileWriter(OUTFILENAME);

Network I/O [ADDITION]

(Not in the textbook)

Review client, server.

The client uses a Socket to communicate with a server (usually over TCP/IP).

The server uses a ServerSocket to accept connections, creating a Socket for each one.

Sockets first appeared in Berkeley Unix (4.2 BSD).

The socket API is part of the Unix/Linux kernel.

Winsock is a user-space program library for Windows.

Java provides sockets in the java.net package, which works for either platform.

java.net.Socket Constructor and Methods

Socket(String host, int port)   // constructor, tries to open
  throws UnknownHostException,  // a connection
         IOException

InputStream getInputStream()    // you can create a Scanner to read
  throws IOException            // from the Socket

OutputStream getOutputStream()  // you can create a PrintWriter to
  throws IOException            // write to the Socket

void close()                   // closes the connection
  throws IOException

java.net.ServerSocket Constructor and Methods

ServerSocket (int port)  // constructor, binds to a port
  throws IOException

Socket accept ()         // waits for a connection,
  throws IOException     // returns a Socket

void close ()            // closes the ServerSocket
  throws IOException

Examples

Client/server applications

  1. Hello
  2. Pig Latin

Important design pattern: Separate the interface (user interface or network interface) from the application logic, because you may want to change the interface — from a desktop application to a web application, for example.

11.7 Tool Tips and Mnemonics

Skip

11.8 Combo Boxes

These are "drop down" menus implemented by the JComboBox class.

Set the options either by passing an array of strings to the constructor, or by using the addItem method.

A combo box fires an ActionEvent when a selection is made, and responds to the getSelectedIndex() method with the selection number (≥ 1 if anything is selected?)

Listings 11.11-11.12 Jukebox/JukeBoxControls illustrates. Additional features illustrated:

This example could be better written with an array of URLs.

11.9 Scroll Panes

Skip

11.10 Split Panes

Skip most of this, but point out the JList class, displayed after Listing 11.14 on p. 575 and described on that page and p. 577.

Discussion

Exercises, p. 580: EX 11.2-11.3

Programming Projects, pp. 580-581:


  1. Revision log:
    • Version 2.3, 2012 Mar 24, updated for 7th edition, fixed some formatting problems, clarified redirection of I/O, highlighted filter stream patterns and design pattern, added examples Redirectable.java and FileIO3.java.
    • Version 2.2, 2010 April 1, added links and commentary to examples.
    • Version 2.1, 2010 March 30, converted to markdown.
    • Version 2, 2009 March 11, revised for 6th edition.