CS 051 Fall 2012

Lecture 34

Checked vs Unchecked Exceptions

There are two main categories of Java exceptions: checked and unchecked.

All of the exceptions we've seen in class so far are considered unchecked. This means
that handling them is optional. We don't have to do anything special in the code where these
exceptions may occur.

There are also checked exceptions in Java. In the cases where we call a method that
may throw a checked exception, we must tell Java what to do with the exception.
There are two ways we can do this. We've seen one already, we can wrap the relevant code in a
try-catch block. We'll see the other technique soon.

Streams

A Java Stream is what we use in Java to move data either into or out of our program.
For example, it is often convenient to save program information to a file, so that the work
can be resumed at a later time. In Java, we use a Stream object to access a file.

To read from a file:

Lots of things can go wrong when we try to access files on the disk. For example:

All of these problems will cause an IOException to be thrown. This is important
because IOExceptions are checked exceptions. That means we have to handle them.

Writing to a file requires similar steps to reading:

Application instead of Applets

So far, we've been writing most, if not all, of our programs as Applets. However, Applets are
restricted from accessing files on the disk, so in order to read or write from a file, we
need to write and Application instead.

Writing Applications differs from Applets in several ways:

The class example ShortWordsFixedFiles demonstrates all of the issues discussed above.