Version 2.31
Handouts:
Exceptions are objects that represent errors or simply unusual events. Examples of kinds of exceptions.
Options for dealing with 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.
try-catch StatementThis 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.
finally clause?Listing 11.2 ProductCodes illustrates catching exceptions.
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.
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
...
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:
System.in (stdin, Unix file descriptor 0)System.out (stdout, Unix file descriptor 1)System.err (stderr, Unix file descriptor 2)These are normally connected to the keyboard and display devices, but may be redirected using the facilities of the operating system.
(Not in the textbook)
< source or 0< source — redirects stdin> sink or 1> sink — redirects stdout>> sink — redirects stdout with append mode2> sink — redirects stderr; can be combined with > sink&> sink — redirects stdout and stderr| process — pipes output to processExamples: 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.
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.
FileReader/FileWriter = a character stream from/to a file; this is a source or sink of data.BufferedReader/BufferedWriter = adds buffering to above (more efficient file I/O); this is a filter.PrintWriter = adds the methods print and println to the above; this is a filter.Scanner = adds Scanner methods to an input stream; this is a filter.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.
Develop a program to read a file of numbers and output their squares:
stdin, stdout, with redirection: FileIO1.javaUseful patterns:
Scanner fileIn =
new Scanner(new FileReader(newBufferedReader(INFILENAME);
PrintWriter fileOut =
new PrintWriter(newBufferedWriter(new FileWriter(OUTFILENAME);
(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 MethodsSocket(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 MethodsServerSocket (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
Client/server applications
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.
Skip
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:
java.applet.AudioClip representing a sound file (.wav)This example could be better written with an array of URLs.
Skip
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.
Exercises, p. 580: EX 11.2-11.3
Programming Projects, pp. 580-581: