CS 112 Programming 2
Lecture 08
Exception Handling & Text I/O (1)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Chapter 12 Exception Handling
and Text IO
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
Motivation
When a program runs into a runtime error, the program
terminates abnormally
How can you handle the runtime error so that the program
can continue to run or terminate gracefully?
This is the subject we will introduce in this chapter
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
Objectives
To get an overview of exceptions and exception handling (§12.2).
To explore the advantages of using exception handling (§12.2).
To distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked vs. unchecked (§12.3).
To declare exceptions in a method header (§12.4.1).
To throw exceptions in a method (§12.4.2).
To write a try-catch block to handle exceptions (§12.4.3).
To explain how an exception is propagated (§12.4.3).
To obtain information from an exception object (§12.4.4).
To develop applications with exception handling (§12.4.5).
To use the finally clause in a try-catch block (§12.5).
To use exceptions only for unexpected errors (§12.6).
To rethrow exceptions in a catch block (§12.7).
To create chained exceptions (§12.8).
To define custom exception classes (§12.9).
To discover file/directory properties, to delete and rename files/directories, and to create directories using the
File class (§12.10).
To write data to a file using the PrintWriter class (§12.11.1).
To use try-with-resources to ensure that the resources are closed automatically (§12.11.2).
To read data from a file using the Scanner class (§12.11.3).
To understand how data is read using a Scanner (§12.11.4).
To develop a program that replaces text in a file (§12.11.5).
To read data from the Web (§12.12).
To develop a Web crawler (§12.13).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 4
Exception Handling
Exception handling enables a program to deal with
exceptional situations and continue its normal
execution
No exception handling Quotient Run
With if-else QuotientWithI Run
f
With a method QuotientWithMethod Run
With try-catch QuotientWithException Run
The benefit of using try-catch is that it enables a method to
throw an exception to its caller method. Without this capability, a
method must handle the exception itself or terminate the program
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 5
InputMismatchException
Another way to handle similar exceptions is with the help
of the InputMismatchException class
Example:
When executing input.nextInt(), an
InputMismatchException occurs if the input entered is
not an int and the control is transferred to the catch block
The statements in the catch block are now executed
InputMismatchExceptionDemo Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 6
Exception Types
Exceptions are objects based on the superclass java.lang.Throwable
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
Error VirtualMachineError
Many more classes
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 7
Checked & Unchecked Exceptions
Throwable
Exception Error
All other exceptions RuntimeException
subclasses subclasses subclasses
Checked Exceptions Unchecked Exceptions
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 8
Errors caused These rare internal system
by your errors are thrown by JVM.
program and If one occurs, notify the user
external Throwable and terminate the program
circumstances
Exception Error
Caused by coding faults
All other exceptions RuntimeException like bad casting, out-of-
bounds array, etc.
subclasses subclasses subclasses
Checked Exceptions Unchecked Exceptions
Program does not compile They happen only after the
if any of these are present
Liang, Introduction programs
to Java Programming, Tenth Edition, (c) 2015 Pearson starts running
Education, Inc. All
9
rights reserved.
Handling Unchecked Exceptions
In most cases, unchecked exceptions reflect programming
logic errors that are not recoverable. For example:
o A NullPointerException is thrown if you access an object
through a reference variable before an object is assigned to it
o An IndexOutOfBoundsException is thrown if you access
an element in an array outside the bounds of the array
These logic errors should be corrected in the program
Unchecked exceptions can occur anywhere in the program
To avoid cumbersome overuse of try-catch, Java does not
mandate you to write code to catch unchecked exceptions
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 10
Declaring, Throwing and Catching
Java’s exception-handling model is based on three operations:
1. Declaring an exception
2. Throwing an exception
3. Catching an exception
Exceptions are declared in and thrown from a method. The
caller of that method can catch and handle the exception
method1() { declare exception
method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 11
Declaring Exceptions
Every method must state the types of checked exceptions
it might throw
This is known as declaring exceptions
Examples:
public void myMethod() throws IOException
public void myMethod()
throws IOException, OtherException
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 12
Throwing Exceptions
When the program detects an error, the program can
create an instance of an appropriate exception type
and throw it
This is known as throwing an exception
Examples:
throw new TheException();
TheException ex = new TheException();
throw ex;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 13
Example: Throwing Exception
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 14
Catching Exceptions
When an exception is thrown, it can be caught and handled
in a try-catch block. If no exceptions arise during the
execution of the try block, the catch blocks are skipped
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
// handler for exception1
}
catch (Exception2 exVar2) {
// handler for exception2
}
...
catch (ExceptionN exVarN) {
// handler for exceptionN
}
If an exception is not caught in the current method, it is
passed to the calling method. The process is repeated
until the exception is caught or passed to main()
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 15
Example: Catching Exceptions An
main method { method1 { method2 {
... ... ... exception
try { try { try { is thrown
... ... ... in
invoke method1; invoke method2; invoke method3; method3
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }
1. If the exception type is Exception3, it is caught by the catch block
for ex3 in method2. statement5 is skipped, and statement6 is
Call Stack executed
method3
method2 method2
method1 method1 method1
main method main method main method main method
2. If the exception type is 3. If the exception type is 4. If the exception type is
Exception2, method2 is aborted, Exception1, method1 is aborted, not caught in method2,
control is returned to method1, control is returned to main, and method1, or main, the
and the exception is caught by the exception is caught by the program terminates,
the catch block for ex2 in catch block for ex1 in main. and statement1 and
method1. statement3 is skipped. statement1 is skipped. statement2 are not
statement4 is executed statement2
Liang, Introduction to Java Programming, is executed
Tenth Edition, (c) 2015 Pearson Education, Inc. Allexecuted
rights reserved. 16
Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares
a checked exception, you must invoke it in a try-catch block or
declare to throw the exception in the calling method
Example:
void p2() throws IOException {
if (file closed) throw new IOException("File is closed");}
If p1() invokes p2() then we must write code as shown in (a) or (b)
void p1() { void p1() throws IOException {
try {
p2(); p2();
}
catch (IOException ex) { }
...
}
}
(a)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. (b) 17
Example: Declaring/Throwing/Catching Checked Exception
This example demonstrates declaring, throwing, and
catching exceptions by modifying the setRadius() in
the Circle class defined in Chapter 9
The new setRadius() throws an exception if radius is
negative
CircleWithException
TestCircleWithException Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 18
Rethrowing Exceptions
An exception handler can rethrow the exception if the handler can’t
process the exception or simply wants to let its caller be notified of
the exception
try {
// statements
}
catch(TheException ex) {
// perform some operations
throw ex;
}
The catch block first catches and processes the
exception, and then rethrows it to the caller so that
other handlers in the caller get a chance to process
ex
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 19
The finally Block
The code in the finally block is executed under all
circumstances, regardless of whether an exception occurs in
the try block or whether an exception is caught if it occurs
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 20
animation
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 21
animation
Trace a Program Execution
The final block is
try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 22
animation
Trace a Program Execution
Next statement in the
try { method is executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 23
animation
Trace a Program Execution
try { Suppose an exception
statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 24
animation
Trace a Program Execution
try { The exception is
statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 25
animation
Trace a Program Execution
try { The final block is
statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 26
animation
Trace a Program Execution
try { The next statement in
statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 27
animation
Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3;
}
Exception2.
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 28
animation
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 29
animation
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 30
animation
Trace a Program Execution
try {
statement1; Rethrow the exception
statement2; and control is
statement3;
}
transferred to the caller
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 31
CS 112 Programming 2
Lecture 09
Exception Handling & Text I/O (2)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
First Midterm Exam
• Monday, 29 February (same time as the lecture)
• 75 minute duration
• Will cover all lectures delivered before the exam date
• Will consist of MCQ’s, fill-in-the-blanks, questions with short
answers, programming tasks, and drawing of diagrams
• If you miss this exam for any reason, you will have to appear
for a makeup exam on the Thursday of the last week of
teaching (5 May). That exam will cover all lectures delivered
in the semester. It will consist of programming tasks, drawing
of diagrams and answering questions having 0.5-1 page
answers
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Pros & Cons of Exception Handling
Advantage: Code is easier to understand and modify
Exception handling separates error-handling code from
normal programming tasks, thus making programs easier to
read and to modify
Drawback: Slower performance, higher resource requirement
Be aware, however, that exception handling usually
requires more time and resources because it requires
instantiating a new exception object, rolling back the call
stack, and propagating the errors to the calling methods
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 34
When to Use Exceptions Handling?
Use try-catch blocks to deal with unexpected error
conditions
Do not use them to deal with simple, expected situations
Example: 2nd block of code is preferable over the 1st
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 35
When to Throw Exceptions?
When an exception occurs in a method,
– if we want the exception to be processed by its caller,
we should create an exception object and throw it
– if we can handle the exception in the method where it
occurs, there is no need to throw it
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 36
Custom Exception Classes
Define custom exception classes only if Java’s
predefined built-in classes are not sufficient
Define custom exception classes by extending
Exception or a subclass of Exception
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 37
Example: Custom Exception Class
In Listing 12.7, setRadius() throws an exception if the
radius is negative. Suppose you wish to pass the radius
to the handler, you have to create a custom exception class
InvalidRadiusException
CircleWithRadiusException
TestCircleWithRadiusException Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 38
The File Class
The File class contains the methods for obtaining the properties
of a file/directory and for renaming and deleting a file/directory
File is intended to provide an abstraction that deals with most
of the machine-dependent complexities of files and path names
in a machine-independent fashion
File is a wrapper class for the filename and its directory path
A File object encapsulates the properties of a file or a path, but
does not contain the methods for reading/writing content from/to
a file
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 39
The
File
Class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 40
Example: Explore File Properties
Objective: Write a program that demonstrates how to create
files in a platform-independent way and use the methods in the
File class to obtain their properties. The following figures
show a sample run of the program on Windows and on Unix.
TestFileClass Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 41
Text I/O
A File object does not contain the methods for reading/
writing content from/to a file
In order to perform I/O, you need to create objects using
appropriate Java I/O classes
We can read/write strings and numeric values from/to a
text file using Scanner and PrintWriter class objects
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 42
Writing Data Using PrintWriter
java.io.PrintWriter
+PrintWriter(filename: String) Creates a PrintWriter for the specified file.
+print(s: String): void Writes a string.
+print(c: char): void Writes a character.
+print(cArray: char[]): void Writes an array of character.
+print(i: int): void Writes an int value.
+print(l: long): void Writes a long value.
+print(f: float): void Writes a float value.
+print(d: double): void Writes a double value.
+print(b: boolean): void Writes a boolean value.
Also contains the overloaded A println method acts like a print method; additionally it
println methods. prints a line separator. The line separator string is defined
Also contains the overloaded by the system. It is \r\n on Windows and \n on Unix.
printf methods. The printf method was introduced in §4.6, “Formatting
Console Output and Strings.”
. WriteData Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 43
try-with-resources
Programmers often forget to close the file. JDK 7
provides the following try-with-resources syntax that
automatically closes files
try (declare and create resources) {
Use the resource to process the file;
}
WriteDataWithAutoClose Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 44
Reading Data Using Scanner
java.util.Scanner
+Scanner(source: File) Creates a Scanner object to read data from the specified file.
+Scanner(source: String) Creates a Scanner object to read data from the specified string.
+close() Closes this scanner.
+hasNext(): boolean Returns true if this scanner has another token in its input.
+next(): String Returns next token as a string.
+nextByte(): byte Returns next token as a byte.
+nextShort(): short Returns next token as a short.
+nextInt(): int Returns next token as an int.
+nextLong(): long Returns next token as a long.
+nextFloat(): float Returns next token as a float.
+nextDouble(): double Returns next token as a double.
+useDelimiter(pattern: String): Sets this scanner’s delimiting pattern.
Scanner
ReadData Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 45
Example: PrintWriter & Scanner
Objective: Write a class named ReplaceText that replaces a string in
a text file with a new string. The filename and strings are passed as
command-line arguments as follows:
java ReplaceText sourceFile targetFile oldString newString
For example, invoking
java ReplaceText s.txt t.txt apple orange
replaces all the occurrences of apple by orange in s.txt and saves
the new file in t.txt
ReplaceText Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 46
Reading Data from the Web
Just like we can read data from a file on your computer,
we can also read data from a file on the Web
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 47
Reading Data from the Web
URL url = new URL("http://google.com/index.html");
After a URL object is created, you can use openStream()
defined in the URL class to open an input stream and use this
stream to create a Scanner object as follows:
Scanner input = new Scanner(url.openStream());
ReadFileFromURL Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 48
Case Study: Web Crawler
Web Crawler: Program that traverses the Web by following URLs
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 49
Case Study: Web Crawler
To ensure that each URL is traversed only once,
the Web crawler maintains two lists of URLs:
1. List of URLs pending for traversing
2. List of URLs that have already been traversed
Add the starting URL to a list named listOfPendingURLs;
while !listOfPendingURLs.isEmpty() && listOfTraversedURLs.size()<= 100 {
Remove a URL from listOfPendingURLs;
if this URL is not in listOfTraversedURLs {
Add it to listOfTraversedURLs;
Display this URL;
Read the page from this URL & for each URL contained in the page {
Add it to listOfPendingURLs if it is not in listOfTraversedURLs;
}
}
}
WebCrawler Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 50