Richard's J2SE Day 7
Threads and Exceptions

=================================================================
Old notes from "Sams Teach Yourself Java 2 in 21 Days" (still vaild, but different page number)
=================================================================

(P179)
Threads: objects that implement the Runnable interface and can run simultaneously with other parts of a Java program. (seperate the computing-intensive parts of a program)
Exceptions: objects that are used to handle errors that may occur as a Java program is running.

Exceptions (P180)
Exception Classes (P182)
Program quits => errors thrown (exceptions)
Exceptions in Java are actual objects (instances of claseses that inherit from the class Throwable)

Exception Classes

Throwable Class
Error Class Exception Class
Errors in Java runtime environment

Runtime Exceptions
Classes

Other Exceptions
Classes

Most of the exception classes are part of the java.lang package (including Throwable, Exception and RuntimeException).
Other packages defines other exceptions.

Managing Exceptions (P183)
try, catch, finally keywords

Exception Consistency Checking
A method can indicate the kinds of errors it might possible throw. When you use those methods in your own Java programs, you have to protect the code against those exceptions.

Protecting Code and Catching Exceptions (P184)
try = protect the code that contains the method that might throw an exception
catch = deal with an exception

try {
float in = Float.parseFloat(input);
} catch (NumberFormatException nfe) {
System.out.println(input + " is not a valid number.");
}

Catch groups of exception => the first catch block that matches will be executed and the rest ignored

try {
// code that might generate exceptions
} catch (IOException e) {
// handle IO exceptions
} catch (ClassNotFoundException e) {
// handle class not found exceptions
} catch (InterruptedException e) {
// handle interrupted exceptions
}

The finally Clause (P186)
There is some action that you must do, no matter whether an exception is thrown or not.

try {
readTextfile();
} catch (IOException e) {
// deal with IO errors
} finally {
closeTextfile();
}

skipped example P186 HexRead.java

Delcaring Methods that Might Throw Exceptions
To indicate that some code in your method's body may throw an exception, add throw keyword after the signature for the method

public boolean myOtherMethod (int x, int y) throws NumberFormatException, EOFException, InterruptedException{
// ......
}

you can use a superclass of an exceptions group to indicate your method may throw any subclass of that exception

Which Exceptions Should You Throw? (P189)
You do not have to list all the possible exceptions that your method could throw.
Implicit exceptions are exceptions that are RuntimeException and Error subclasses.
All other exceptions are called explicit exceptions and are potential candidates for a throw clause in your methods.

Passing on Exceptions (P190)
There are times where it doesn't make sense for your method to deal with the exception. It might be better for the method that calls your method to deal with that exceptions.
Just throws the exception to pass it on.

throws and Inheritance (P191)
If your method definition overrides a method in a superclass that includes a throws clause......
your new method does not require the same set of exceptions listed in the throws clause.
Because your new method might deal better with exceptions other than just throwing them, your method can potentially throws fewer types of exceptions.

Creating and Throwing Your Own Exceptions (P192)
Throwing Exceptions (P192)
Declaring that your method throws an exceptions... does not do anything to actually throw... you have to do that in the body of the method.
Need to create a new instance of an exception class to throw an exception.

NotInServiceException() nis = new NotInServiceException("Exception: Database Not in Service");
throw nis;

Creating Your Own Exceptions (P193)
All user-created exceptions should be part of the Exception hierarchy rather than the Error hierarchy.
If you cannot find a closely related exception for your new exception, consider inheriting from Exception, which forms the top of the expection hierarchy for explicit exceptions.

Exception classes typically have two constructors: The first takes no arguments and the second takes a single string as an argument.

Beyond these rules, exception classes look just like other classes.

public class SunSpotException extends Exception {
public SunSpotException() {}
public SunSpotException(String msg) {
super(msg);
}
}

Combining throws, try and throw (P193)
You'd like to handle the incoming exceptions yourself in your methods, but also like the option to pass the exception to your caller.

public vodi readMessage() throws IOException {
MessageReader mr = new MessageReader();
try {
mr.loadHeader();
} catch (IOException e) {
// do something to handle the
// IO Exception
throw e; // rethrow the exception
}
}

When to When Not to Use Exceptions (P194)
When to Use Exceptions (P194)
You can do 3 things if your methods calls another method that has a throws clause:

When Not to Use Exceptions (P195)
There are several cases in which you should not use exceptions

Bad Style Using Exceptions (P195)
Add an empty catch clause or to add a throw statement to your own method

Assertions (P196)
An expression that represents a condition that a programmer believes to be true at a specific place in a program. If it isn't true, an error results.

assert price > 0 :"Price less than 0.";

To compile a class that contains assert statement use the -source 1.4 argument

java -source 1.4 PriceChecker.java

Threads (P198)
How system resources are being used. (GUI)
Segregate the processing-hogging functions in a Java program so that they run seperately from the rest of the program. (multitasking)

Writing a Threaded Program (P198)
Thread class in the java.lang package.
To modify a class so that it uses threads, the class must implement the Runnable interface in the java.lang package.

public class StockTicker implements Runnable {
public void run() {
// .......
}
}


The runnable interface contains only one method run().
Threads are created by calling the constructor Thread(object) with the threaded object as an argument.

Three good places to create threads are

Calling a thread's start() method causes another method to be called - the run() method that must be present in the threaded object.

A Threaded Application (P200)
Threaded programming requires a lot of interaction among different objects.
(P200) PrimeFinder.java
The PrimeFinder implements the Runnable interface, so it can be run as a thread.
This class doesn't have a main() method, (P202) PrimeThreads.java uses the PrimeFinder class.
To run application .... java PrimeThreads 1 10 100 1000

PrimeThreads application creates one PrimeFinder object for each command-line argument.
Thread.sleep(1000) causes the while loop to pause for one second during each pass through the loop

Stopping a Thread
(P204)
Thread class includes a stop() method, but it has been deprecated in Java 2 because of instabilities.
Another way to stop a thread

public void run() {
while (okToRun == true) {
// ....
}
}

The okToRun variable could be instance variable of the thread's class, if it is changed to false, the loop will end.

Exercises (P208) ....

 

=================================================================
New notes from "Sams Teach Yourself Java 6 in 21 Days"
=================================================================