You are on page 1of 28

Topics in this lecture

 General discussion of Exceptions


 Focus on Checked Exceptions
 Files and Streams
 Reading and Writing Text Files
Exception Handling

Ch.11 of Horstmann 6th edition

– Exception: indication of problem during execution


– Example: array out of bounds
– Handles errors
– Class Exception
What is an Exception?

• An error event that disrupts the program flow and


may cause a program to fail.
• Some examples:
– Performing illegal arithmetic operations
– Illegal arguments to methods
– Accessing an out-of-bounds array element
– Hardware failures
– Writing to a read-only file
– …
Exception Terminology

• When an exception happens we say it was thrown


or raised
• When an exception is dealt with, we say the
exception is/was handled or caught
Exception Hierarchy

• All exceptions are instances of classes that are


subclasses of Exception
Unchecked Exception Example

public static int average(int[] a) {


int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}return total / a.length;
}

What happens when this method is used to take the average


of an array of length zero?

Program throws an Exception and fails. The message is:


java.lang.ArithmeticException: division by zero
Customizing the message

public static int average(int[] a) {


int total = 0;
for(int i = 0; i < a.length; i++)
total += a[i];
return total / a.length;
}
public static void printAverage(int[] a) {
try {
int avg = average(a);
System.out.println("the average is: " + avg);
}
catch(ArithmeticException e) {
System.out.println("error calculating average");
}
}
The try-catch blocks

try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
Catching Multiple Exceptions

• Handle multiple possible exceptions by multiple


successive catch blocks
try {
// code that might throw multiple exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
}
Another Example

public class ExceptionExample {


public static void main(String args[]) {
String[] greek = {"Alpha","Beta"};
System.out.println(greek[2]);
}
}

Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2 at
ExceptionExample.main(ExceptionExample.java:4)
Exception Message

• Exception message format


– [exception class]: [additional description of exception]
at [class].[method]([file]:[line number])

• Example
– java.lang.ArrayIndexOutOfBoundsException: 2 at
ExceptionExample.main(ExceptionExample.java:4)
– What exception class?
– Which array index is out of bounds?
– What method throws the exception?
– What file contains the method?
– What line of the file throws the exception?
Unchecked Exceptions

• All the exceptions we've seen so far have been


Unchecked Exceptions (RuntimeException,
Error, and their subclasses)
• Usually occur because of programming errors,
when code is not robust enough to prevent them
• They are numerous and can sometimes be ignored
by the programmer in the method signature
– methods are not obliged to handle unchecked exceptions
Checked Exceptions

• Usually occur because of errors that programmers


cannot control, e.g.,
– hardware failures,
– unreadable files
• They are less frequent and they cannot be ignored
by the programmer.
• We shall deal with them in the lectures on Files
and Multithreading.
Dealing with Checked Exceptions

• Every method must catch (handle) checked exceptions


void readFile(String filename) {
try {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
} catch(FileNotFoundException e){
System.out.println("file was not found");
}
}
• The alternative is to use “throws” followed by the
Exception class name:
void readFile(String filename) throws FileNotFoundException{
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
}
Files and Streams

• Chapter 11 and 19 in Horstmann 6th edition

Files
– Long-term storage of large amounts of data
– Persistent data exists after termination of program
– Files stored on secondary storage devices
• Magnetic disks
• Optical disks
• Magnetic tapes
– Sequential and random access files
Files and Streams

• The use of input/output files require the use of the


class File.
• This class can work together with class Scanner
for an input file case and class PrintStream for an
output file case.
• Next slide shows an example in which the content
of input file “input.txt” are integers (one per line)
and the content of the output file “output.txt” is
“The sum is:“ followed by the sum of the integers
in the input file.
Reading and Writing Text Files

import java.util.Scanner;
import java.io.*;

public class ExampleFile{


public static void main(String[] args) throws IOException{
Scanner fileInput = new Scanner(new File("input.txt"));
PrintStream fileOutput = new PrintStream(new File("output.txt"));

int sum = 0;
for( ; fileInput.hasNextInt(); ){
sum = sum + fileInput.nextInt();
}
fileOutput.println("The sum is: " + sum);
fileInput.close();
fileOutput.close();
}
}
Reading and Writing Files – Alternative code
catch (IOException exception) {
import java.util.Scanner; System.out.println("File not found");
import java.io.*; }
catch (NumberFormatException exception) {
public class ExampleFile1{ System.out.println("Input was not a
public static void main(String[] args) { number");
}
int sum = 0;
finally{
Scanner fileInput=null; fileOutput.println("The sum is: " + sum);
PrintStream fileOutput=null; fileInput.close();
fileOutput.close();
try { }
fileInput = new Scanner(new File("input.txt")); }
}
fileOutput = new PrintStream (new
File("output.txt"));
// this version is better because it catches
for( ; fileInput.hasNextLine(); ){ // wrong data in the input file
String s = fileInput.nextLine();
sum = sum + Integer.parseInt(s);
}
}
Buffering

• Buffering
– Improves performance of I/O
– Copies each output to a region of memory called a buffer
– Entire buffer output to disk at once
• One long disk access takes less time than many smaller ones
– A program can convert an unbuffered stream into a buffered
stream
• Example

inputStream = new BufferedReader(new FileReader("xanadu.txt"));


outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));
A Business Example

This program deals with reading information


from an Inventory.dat file. The data is entered
into an input buffer from where it is read line by
line. The code has to signal any errors in the
reading of the components of each line.

The data read from the file is used to create an


array of InventoryItem objects, which are
displayed at the end of the data entry code.
The File Inventory.dat

In this example one processes the information stored in the text file
“Inventory.dat”. Each line of this file contains: the name of the
product, the number of items and the price per item, separated by a
space.

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
Creating an array of objects with data from a text file

import java.util.*;
import java.io.*;
import java.text.*;

public class Inventory{

public static void main (String[] args) {

final int MAX = 100;


InventoryItem[] items = new InventoryItem[MAX];
StringTokenizer tokenizer;
String line, name, file=“Inventory.dat";
int units, count = 0;
float price;

try{

FileReader fr = new FileReader (file);


BufferedReader inFile = new BufferedReader (fr);
line = inFile.readLine();

// the external file contains each line of data like in the example: chairs 4 45.50

while (line != null) {


tokenizer = new StringTokenizer (line);
name = tokenizer.nextToken();
Continue..
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();

} // end of the while

infile.close()
for (int scan = 0; scan < count; scan++)
System.out.println (items[scan]);

} // the end of the first try

// the next catches relates to the first try

catch (FileNotFoundException exception) {


System.out.println ("The file " + file + " was not found.");
}
catch (IOException exception) {
System.out.println (exception);
}
}
}
class InventoryItem used in Inventory.java

Continue..
class InventoryItem {
private String name;
private int units; // number of available units of this item
private float price; // price per unit of this item
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));
}
}
The Business Example as a Frame

We modify the class Inventory to be a JFrame


application. The GUI of this program contains
only a button which is used to read from the
Inventory.dat file one record at a time entering
the data in textfields. These textfields have the
following labels:
- Product name
- Number of units
- Price per unit
Class Inventory as a Frame with Action
import java.util.StringTokenizer;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class InventoryFrame extends JFrame implements ActionListener{


StringTokenizer tokenizer;
String line, file="Inventory.dat";
JTextField t1, t2, t3;
JButton get;
BufferedReader inFile;

public InventoryFrame() {
setSize(300,200);
show();
try {
FileReader fr = new FileReader (file);
inFile = new BufferedReader (fr);
}
catch (IOException ex){
System.out.println ("File missing.");
}
Container c = getContentPane();
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4,2));
p1.add(new JLabel("Product name"));
Class Inventory as a Frame with Action (II)
t1 = new JTextField(10);
p1.add(t1);
p1.add(new JLabel("Number of units"));
t2 = new JTextField(10);
p1.add(t2);
p1.add(new JLabel("Price per unit"));
t3 = new JTextField(10);
p1.add(t3);
get=new JButton("Get Record from Text File");
p1.add(get);
get.addActionListener(this);
c.add(p1,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
try { line = inFile.readLine(); }
catch (IOException ex){}
if (line != null){
tokenizer = new StringTokenizer (line);
t1.setText(tokenizer.nextToken());
t2.setText(tokenizer.nextToken());
t3.setText(tokenizer.nextToken());
}
} // end actionPerformed()

public static void main( String args[] ) {


InventoryFrame app = new InventoryFrame();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
Writing a text file

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.txt";
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);
}
}

You might also like