Exceptional conditions can stop a program abruptly before it completes its intended work.
Examples of exceptions include:
·
Issue
a command to read a non-existent file.
·
User
enters invalid data
·
Divide
by zero
·
Subscript
that is too large for the array
·
Calculate
a value that is too large for the variable’s type.
“Errors” are normally generated by the System:
·
bugs
in the Java VM, or hardware limitations (out of memory or other resources).
·
these
errors are not handled within a program.
“Exceptions” are generally Programmer errors:
·
Bugs
within the program or unexpected data supplied to the program
·
can
be caught and handled within a program
“Exception”
is also a Java class
that creates an object describing the “exceptional”
situation
Some
approaches for handling error conditions
·
Ignore potential errors.
Most of the time, let Java terminate the program when an error occurs. While the program is “down,” the programmer will have to analyze the cause, fix the condition, test program changes, then rerun the program.
Advantage: The program
code is minimal and clearly focused toward what should be accomplished.
Disadvantage:
If
the program is crucial, workflow of users may be impaired, schedules may not be
met, employees may be idle, or laid-off.
·
Test for all possible errors before processing the data.
Advantage: Potential
errors will be recognized and avoided.
The program will be “down” a minimum amount of time.
Disadvantage:
Program
code becomes larger and the processing time of the program is increased as it
checks all data and conditions for possible error. If the error checking tasks is intermixed with the regular
processing tasks, the program code
becomes harder to understand.
·
Try to execute code. If it
doesn’t work, catch the errors and process them.
Advantage: A block of
code will be clearly focused toward achieving a given task. Exceptional events are grouped and not in
the way of the primary task. Errors
will only be processed if they occur.
The program will be “down” a minimum amount of time.
Disadvantage:
Program
code becomes larger.
try {
// Statements that may cause Exception1
or Exception2
// If no statement causes an exception,
then the
// catch blocks will not be
executed. If an exception
// occurs, statement processing finds the
first
// appropriate catch block.
}
catch (Exception1 e1) { // catch can
handle one type of exception
// handle Exception1 – what to do about
it
System.out.println(“Error is “ +
e1.getMessage());
}
catch (Exception2 e2) {
// handle Exception2
System.out.println(“Error is “ +
e2.getMessage());
}
catch (Exception error) {
// a generic “catch-all” block to handle any
Exception
// other than
Exception1 or Exception2
System.out.println(“Error
is “ + error.getMessage());
// put catch-all blocks after the more
specific error blocks
}
finally {
// optional code always executed
after try block completes
// whether an exception is
thrown or not
// typically used to do program clean up
operations like
// closing files which were opened for
processing
}
There must be at least one catch
block following a try block.
Program Example: ProductCodes.java
import java.io.*;
public class ProductCodes {
public static void
main (String[] args) throws IOException
{
String code = "
";
char zone = '\t';
int district = 0,
entered = 0, banned = 0;
BufferedReader br =
new BufferedReader
(new
InputStreamReader (System.in));
System.out.print
("Enter product code (XXX to quit): ");
code = br.readLine();
while (!code.equals
("XXX")) {
try {
zone =
code.charAt(4);
district =
Integer.parseInt(code.substring(0, 4));
entered++;
if (zone == 'R'
&& district > 2000)
banned++;
} // end of try
catch
(StringIndexOutOfBoundsException exception) {
System.out.println
("\t" + exception.getMessage()
+ " Product
Code should be at least 5 characters:");
} // end of catch
catch
(NumberFormatException exception) {
System.out.println
("\tCharacters 1 though 4 should be numeric: "
+ " " +
exception.getMessage());
} // end of catch
System.out.print
("Enter product code (XXX to quit): ");
code =
br.readLine();
} // end of while
System.out.println
("# of non-exception codes entered: " + entered);
System.out.println
("# of banned codes entered: " + banned);
}
}
Class Structure to Define Your Own Exception
public class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
public class OutOfRangeException extends Exception {
// Sets up the exception object
with a particular message.
OutOfRangeException (String message) {
super (message);
}
}
Throw Statement and Throws Clause
The programmer can generate an exception by executing a “throw” statement.
throw
anException
If your program might throw a customized
exception, use a “throws” clause.
public class
MyClass {
public void aMethod(int i, int j) throws
MyException {
// ...
throw new MyException(reason);
// ...
}
}
Program
Example: StoppedByException.java
import java.io.*;
public class StoppedByException {
public static void main (String[] args)
throws IOException, OutOfRangeException {
BufferedReader br =
new BufferedReader
(new InputStreamReader
(System.in));
final int MIN = 25, MAX = 40;
OutOfRangeException problem = new OutOfRangeException
("Input value is out of
range.");
System.out.print ("Enter an integer value between "
+ MIN + " and " + MAX +
", inclusive: ");
int value = Integer.parseInt(br.readLine());
if (value < MIN || value > MAX)
throw problem;
System.out.println ("End of main method.");
// may never reach the above
println statement
}
}
Program
Example: CatchException.java
import java.io.*;
public class CatchException {
public static void main (String[] args)
throws IOException {
BufferedReader br =
new BufferedReader
(new InputStreamReader
(System.in));
final int MIN = 25, MAX = 40;
OutOfRangeException problem =
new OutOfRangeException
("Input value is out of
range.");
System.out.print ("Enter an integer value between "
+ MIN + " and " + MAX +
", inclusive: ");
try {
int value = Integer.parseInt(br.readLine());
if (value < MIN || value > MAX)
throw problem;
}
catch (OutOfRangeException exception) {
System.out.println(exception.getMessage());
}
System.out.println ("End of main method.");
// should reach println statement
above
}
}
·
A stream is a sequence
of bytes.
·
In a program, we read
information from an input stream and write information to an output stream
·
An I/O stream is either
a
o
character stream, which
deals with text data
o
byte stream, which deal
with binary data
Stream-based I/O supports reading or writing data
sequentially.
A stream may be
opened for either reading or writing, but not both.
Random access I/O supports reading and writing data
at any position of a file.
A random access
file may be opened for both reading and writing.
Some classes used for I/O
FileInputStream
|
Reads bytes from a file |
|
Reader |
Abstract class for reading character streams |
|
InputStreamReader |
Reads bytes & translates into characters |
|
BufferedReader |
Read character-input and builds lines or arrays |
|
StreamTokenizer |
Parse strings into tokens |
|
OutputStream |
Abstract class to outputting bytes |
|
FileOutputStream |
Write data to a file |
|
Writer |
Write character streams |
If an I/O class does not do everything needed to process input from a file,
“pipe” the output of that class to another class that further refines the data.
Continue building a pipe until the data is in the form needed.
Example of connecting classes via a
“piped” process:
|
text
input file |
ŕ |
FileInputStream |
ŕ |
InputStreamReader |
ŕ |
|
|
|
extracts
bytes from file and
outputs bytes |
|
gets
bytes from Stream and
outputs characters |
|
Common Class Input Combinations
|
Read
character at a time from a text file
|
FileInputStream(fileName) InputStreamReader
|
|
Read one line at a time from a text file |
FileInputStream (fileName) InputStreamReader BufferedReader
|
|
Read
one word at a time from a text file
|
FileInputStream (fileName) InputStreamReader BufferedReader StreamTokenizer
|
|
Read
Keyboard input
|
InputStreamReader(System.in) BufferedReader
|
|
Read
int, double, etc. from a non-text file
|
FileInputStream(fileName) DataInputStream
|
I/O Program Examples
Inventory.dat
Widget
14 3.35
Spoke
132 0.32
Wrap
58 1.92
Thing
28 4.17
Brace
25 1.75
Clip
409 0.12
Cog
142 2.08
ReadCharacters.java (read
the file one character at a time)
import java.io.*;
public class ReadCharacters{
public static void main (String[] args) {
String file="C:/bluej/read/inventory.dat";
int asciiValue;
char ch;
try {
FileInputStream stream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader (stream);
asciiValue = reader.read();
while (asciiValue != -1) {
ch = (char) asciiValue;
System.out.print(String.valueOf(ch));
asciiValue = reader.read();
}
stream.close();
} catch (FileNotFoundException exception) {
System.out.println("The file " + file + "
was not found.");
} catch (IOException exception) {
System.out.println(exception);
}
}
}
ReadLines.java
import java.io.*;
public class ReadLines{
public static void main (String[] args) {
String line, file="C:/bluej/read/inventory.dat";
try {
FileInputStream stream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader (stream);
BufferedReader buffer = new BufferedReader (reader);
line = buffer.readLine();
while (line != null){
System.out.println(line);
line = buffer.readLine();
}
stream.close();
} catch (FileNotFoundException exception) {
System.out.println("The file " + file + "
was not found.");
} catch (IOException exception) {
System.out.println(exception);
}
}
}
ReadWords.java
import java.io.*;
import java.util.StringTokenizer;
public class ReadWords{
public static void main (String[] args) {
String word, line,
file="C:/bluej/read/inventory.dat";
String name;
float price;
int units;
try {
FileInputStream stream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader (stream);
BufferedReader buffer = new BufferedReader (reader);
line = buffer.readLine();
while (line != null){
StringTokenizer
tokenizer = new StringTokenizer (line);
name = tokenizer.nextToken();
try
{
units = Integer.parseInt(tokenizer.nextToken());
price = Float.parseFloat(tokenizer.nextToken());
System.out.println(name + " " + units + "
" + price );
} catch (NumberFormatException exception) {
System.out.println("Error in input. Line
ignored:");
System.out.println(line);
}
line = buffer.readLine();
}
stream.close();
} catch (FileNotFoundException exception) {
System.out.println("The file " + file + "
was not found.");
} catch (IOException exception) {
System.out.println(exception);
}
}
}
import java.text.DecimalFormat;
public class InventoryItem
{
private String name;
private int units;
private float price;
private DecimalFormat fmt;
public InventoryItem(String itemName, int numUnits,
float cost) {
name = itemName;
units = numUnits;
price = cost;
fmt = new DecimalFormat ("0.##");
}
public String toString() {
return name + ":\t" + units + " at " +
price +
" = " + fmt.format ((units * price));
}
}
Inventory.java
import java.util.StringTokenizer;
import java.io.*;
public class Inventory
{
public static void main (String[] args) {
final int MAX = 100;
InventoryItem[] items = new InventoryItem[MAX];
StringTokenizer tokenizer;
String line, name,
file="C:/bluej/read/inventory.dat";
int units, count = 0;
float price;
try {
FileReader fr = new FileReader (file);
BufferedReader inFile = new BufferedReader(fr);
line = inFile.readLine();
while (line != null) {
tokenizer = new StringTokenizer (line);
name = tokenizer.nextToken();
try {
units = Integer.parseInt(tokenizer.nextToken());
price = Float.parseFloat(tokenizer.nextToken());
items[count++] =
new InventoryItem(name, units, price);
}
catch
(NumberFormatException exception) {
System.out.println("Error in input. Line
ignored:");
System.out.println(line);
}
line = inFile.readLine();
}
inFile.close();
for (int scan = 0; scan < count; scan++)
System.out.println(items[scan]);
}
catch (FileNotFoundException exception) {
System.out.println("The file " + file + "
was not found.");
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
ReadLocalFileAsURLStream.java
import java.io.*;
import java.net.*;
public class ReadLocalFileAsURLStream{
public static void main (String[] args) {
String line, file="C:/bluej/read/inventory.dat";
try {
URL URLfile = new URL
("file:///C:/bluej/read/inventory.dat");
InputStream input = URLfile.openStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(input));
line = buffer.readLine();
while (line != null)
{
System.out.println(line);
line = buffer.readLine();
}
}
catch (FileNotFoundException exception) {
System.out.println("The file " + file + "
was not found.");
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
ReadRemoteURLFile.java
import java.io.*;
import java.net.*;
public class ReadRemoteURLFile{
public static void main (String[] args) {
String line, file="http://condor.depaul.edu/~jpetlick/extra/java/inventory.dat";
try {
URL URLfile = new URL (file);
InputStream input = URLfile.openStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(input));
line = buffer.readLine();
while (line != null) {
System.out.println(line);
line = buffer.readLine();
}
}
catch (FileNotFoundException exception) {
System.out.println("The file " + file + "
was not found.");
}
catch (IOException exception) {
System.out.println(exception);
}
}
}
Output
to a file
//********************************************************************
//
TestData.java Author: Lewis and Loftus
//
//
Demonstrates the use of a character file output stream.
//********************************************************************
import java.io.*;
public class TestData {
//-----------------------------------------------------------------
// Creates a file of test data that consists of
ten lines each
// containing ten integer values in the range 0
to 99.
//-----------------------------------------------------------------
public
static void main (String[] args) throws IOException {
final
int MAX = 10;
int
value;
String
file = "test.dat";
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
for (int
line=1; line <= MAX; line++) {
for
(int num=1; num <= MAX; num++) {
value = (int) (Math.random() * 100);
outFile.print (value + "
");
}
outFile.println ();
}
outFile.close();
System.out.println
("Output file has been created: " + file);
}
}