O'Reilly logo

Learning Java Through Games by Lubomir Stanchev

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 13
Exception Handling and Files
13.1 Handling Exceptions .................................................................... 293
13.2 Text Files ............................................................................... 299
13.2.1 The File Chooser Dialog ........................................................ 299
13.2.2 Reading from Text Files ........................................................ 300
13.2.3 Writing to Text Files ........................................................... 303
13.3 Data Files ............................................................................... 306
13.4 Summary ................................................................................ 313
13.5 Syntax .................................................................................. 313
13.6 Important Points ....................................................................... 315
13.7 Exercises ................................................................................ 316
13.8 Lab ...................................................................................... 317
13.9 Project .................................................................................. 317
This chapter covers two important topics: files and exception handling. The topics are
covered together because every time we are working with a file, an exception can occur.
This exception can be that the file does not exist, we do not have permission to open it,
the hard disk is full and we are trying to save the file, and so on. We will cover two types
of files: text and data. For text files, we will read and write regular text to a file. When
it comes to data files, we will read and write objects to a file. We will cover checked and
unchecked exceptions. While Java forces us to handle checked exceptions, such as opening a
file, Java does not require that one handles unchecked exceptions, such as division by zero.
In the spirit of the textbook, we will describe all new Java primitives in the context of
applications. We will first extend the Notepad software and add features to read and write
to a file. Next, we will examine how the data from a bank application can be stored on the
hard disk. The latter is an interesting example because it demonstrates how to store on the
hard disk interlinked objects that belong to a multiple classes.
13.1 Handling Exceptions
Consider an application that wants to read a positive integer from the keyboard. How-
ever, the application should be bullet-proofed. In particular, the application should not
crash if the user enters a string, for example. Below is one possible way to implement such
an application.
import java . uti l . ;
public c la ss Test {
public s ta tic void main( String args [] ) {
int i=1;
while (i <=0) {
i = getNumber () ;
}
293
294 Learning Java through Games
System.out.println(i);
}
public s ta tic int getNumber() {
try {
Scanner console = new Scanner ( System . in ) ;
System . out . p ri n t ("Enter a positive integer : " );
return console . nextInt () ;
} catch ( InputMismatchException exception ) {
return 1;
}
}
}
The getNumber method asks the user to enter an integer and reads the integer. How-
ever, the nextInt method will raise an exception if the user does not enter an integer. An
exception is an object that is automatically generated by Java. Every exception belongs to
an exception class. For example, InputMismatchException is an exception class. An ex-
ception of type InputMismatchException is generated when Java expects an input of one
type (e.g., an integer), but receives an input of a different type (e.g., a string). All exception
classes inherit from the Exception class. In the above code, the exception object is passed
as a parameter in the catch statement, but not used.
To handle an exception, create a try block. The try block must be followed by
either one or more catch blocks, a finally block, or both. The finally block, when
present, must be the last block in the statement.
An InputMismatchException is generated by the call to the nextInt method when the
user does not enter an integer. This exception is handled in the catch part of the statement.
As a result, the getNumber method returns 1 when the user does not enter an integer.
This signals to the main method that something went wrong and the user is required to
enter the integer again. In order for this approach to work, we assume that the user must
enter a positive integer.
Next, suppose that we require that the user enters an arbitrary integer, not just a
positive integer. In this case, the getNumber method should return two pieces of data: the
integer that is entered (assuming it is an integer) and a Boolean value that tells us if the
user entered an integer. Of course, as we already know, a method cannot return two pieces
of data. The only way to circumvent this restriction is to give the method an address where
to write the result. Here is the new implementation.
import java . uti l . ;
public c la ss Test {
public s ta tic void main( String args [] ) {
int a[] = new i n t [1];
int i;
while( ! getNumber(a ) ) ;
i=a[0];
System.out.println(i);
}
p ub l ic static boolean getNumber( int [] a) {

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required