Liang Chapter 12
Liang Chapter 12
Liang Chapter 12
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
1 2
rights reserved. rights reserved.
✦
Objectives
To get an overview of exceptions and exception handling (§12.2). Exception-Handling Overview
✦ 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). Show runtime error
✦ To throw exceptions in a method (§12.4.2).
To write a try-catch block to handle exceptions (§12.4.3).
✦
Quotient Run
✦ 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). Fix it using an if statement
✦ To use exceptions only for unexpected errors (§12.6).
✦ To rethrow exceptions in a catch block (§12.7). QuotientWithIf Run
✦ 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).
With a method
✦ 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). QuotientWithMethod Run
✦ 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 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
3 4
rights reserved. rights reserved.
Exception Advantages Handling InputMismatchException
Now you see the advantages of using exception handling. By handling InputMismatchException, your program will
It enables a method to throw an exception to its caller. continuously read an input until it is correct.
Without this capability, a method must handle the
exception or terminate the program.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
5 6
rights reserved. rights reserved.
ArithmeticException ArithmeticException
IOException IOException
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
7 8
rights reserved. rights reserved.
Exceptions Runtime Exceptions
Exception describes errors
caused by your program ClassNotFoundException ClassNotFoundException
and external
ArithmeticException ArithmeticException
circumstances. These IOException IOException
errors can be caught and
Exception NullPointerException Exception NullPointerException
handled by your program.
RuntimeException RuntimeException
IndexOutOfBoundsException IndexOutOfBoundsException
Many more classes Many more classes
Object Throwable IllegalArgumentException Object Throwable IllegalArgumentException
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
9 10
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
11 12
rights reserved. rights reserved.
Unchecked Exceptions Declaring, Throwing, and
Catching Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException method1() { declare exception
method2() throws Exception {
IndexOutOfBoundsException try {
invoke method2; if (an error occurs) {
Many more classes
}
Object Throwable IllegalArgumentException catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
Many more classes }
LinkageError
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
13 14
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
15 16
rights reserved. rights reserved.
Throwing Exceptions Example Catching Exceptions
try {
/** Set a new radius */ statements; // Statements that may throw exceptions
public void setRadius(double newRadius) }
catch (Exception1 exVar1) {
throws IllegalArgumentException {
handler for exception1;
if (newRadius >= 0)
}
radius = newRadius; catch (Exception2 exVar2) {
else handler for exception2;
throw new IllegalArgumentException( }
"Radius cannot be negative"); ...
} catch (ExceptionN exVar3) {
handler for exceptionN;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
17 18
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
19 20
rights reserved. rights reserved.
Catch or Declare Checked Exceptions Example: Declaring, Throwing, and
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or
Catching Exceptions
RuntimeException), you must invoke it in a try-catch block or declare to
throw the exception in the calling method. For example, suppose that
✦ Objective: This example demonstrates
method p1 invokes method p2 and p2 may throw a checked exception (e.g., declaring, throwing, and catching exceptions
IOException), you have to write the code as shown in (a) or (b). by modifying the setRadius method in the
Circle class defined in Chapter 9. The new
void p1() {
try {
void p1() throws IOException {
setRadius method throws an exception if
p2();
}
catch (IOException ex) {
p2();
radius is negative.
}
...
}
} CircleWithException
(a) (b) Run
TestCircleWithException
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
21 22
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
23 24
rights reserved. rights reserved.
animation animation
Trace a Program Execution Trace a Program Execution
Suppose no
exceptions in the
statements The final block is
try { try { always executed
statements; statements;
} }
catch(TheException ex) { catch(TheException ex) {
handling ex; handling ex;
} }
finally { finally {
finalStatements; finalStatements;
} }
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
25 26
rights reserved. rights reserved.
animation animation
Trace a Program Execution Trace a Program Execution
Next statement in the try { Suppose an exception
method is executed statement1; of type Exception1 is
try { statement2; thrown in statement2
statements; statement3;
} }
catch(TheException ex) { catch(Exception1 ex) {
handling ex;
handling ex;
}
} finally {
finally { finalStatements;
finalStatements; }
}
Next statement;
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
27 28
rights reserved. rights reserved.
animation animation
Trace a Program Execution Trace a Program Execution
try { The exception is try { The final block is
statement1; handled. statement1; always executed.
statement2; statement2;
statement3; statement3;
} }
catch(Exception1 ex) { catch(Exception1 ex) {
handling ex; handling ex;
} }
finally { finally {
finalStatements; finalStatements;
} }
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
29 30
rights reserved. rights reserved.
animation animation
Trace a Program Execution Trace a Program Execution
try {
try { The next statement in statement1; statement2 throws an
statement1; the method is now statement2; exception of type
statement2; executed. statement3; Exception2.
statement3; }
catch(Exception1 ex) {
} handling ex;
catch(Exception1 ex) { }
handling ex; catch(Exception2 ex) {
} handling ex;
finally { throw ex;
finalStatements; }
} finally {
finalStatements;
Next statement; }
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
31 32
rights reserved. rights reserved.
animation animation
Trace a Program Execution Trace a Program Execution
try { try {
statement1; Handling exception statement1; Execute the final block
statement2; statement2;
statement3; statement3;
} }
catch(Exception1 ex) { catch(Exception1 ex) {
handling ex; handling ex;
} }
catch(Exception2 ex) { catch(Exception2 ex) {
handling ex; handling ex;
throw ex; throw ex;
} }
finally { finally {
finalStatements; finalStatements;
} }
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
33 34
rights reserved. rights reserved.
animation
Trace a Program Execution Cautions When Using Exceptions
try {
statement1; Rethrow the exception
statement2; ✦ Exception handling separates error-handling
and control is
}
statement3; transferred to the caller code from normal programming tasks, thus
catch(Exception1 ex) { making programs easier to read and to modify.
handling ex;
} Be aware, however, that exception handling
catch(Exception2 ex) {
handling ex; usually requires more time and resources
}
throw ex;
because it requires instantiating a new exception
finally { object, rolling back the call stack, and
finalStatements;
} propagating the errors to the calling methods.
Next statement;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
35 36
rights reserved. rights reserved.
When to Throw Exceptions When to Use Exceptions
✦ An exception occurs in a method. If you want When should you use the try-catch block in the code?
You should use it to deal with unexpected error
the exception to be processed by its caller, you conditions. Do not use it to deal with simple, expected
should create an exception object and throw it. situations. For example, the following code
If you can handle the exception in the method
try {
where it occurs, there is no need to throw it.
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
37 38
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
39 40
rights reserved. rights reserved.
Companion
Custom Exception Class Example Website
Assertions
In Listing 13.8, the setRadius method throws an exception if the An assertion is a Java statement that enables
radius is negative. Suppose you wish to pass the radius to the
handler, you have to create a custom exception class.
you to assert an assumption about your
program. An assertion contains a Boolean
expression that should be true during
program execution. Assertions can be used to
assure program correctness and avoid logic
InvalidRadiusException
errors.
CircleWithRadiusException
TestCircleWithRadiusException Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
41 42
rights reserved. rights reserved.
Companion Companion
Website
Declaring Assertions Website
Executing Assertions
An assertion is declared using the new Java keyword When an assertion statement is executed, Java evaluates the
assert in JDK 1.4 as follows: assertion. If it is false, an AssertionError will be thrown. The
AssertionError class has a no-arg constructor and seven
overloaded single-argument constructors of type int, long, float,
assert assertion; or double, boolean, char, and Object.
assert assertion : detailMessage;
For the first assert statement with no detail message, the no-arg
where assertion is a Boolean expression and constructor of AssertionError is used. For the second assert
detailMessage is a primitive-type or an Object value. statement with a detail message, an appropriate AssertionError
constructor is used to match the data type of the message. Since
AssertionError is a subclass of Error, when an assertion becomes
false, the program displays a message on the console and exits.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
43 44
rights reserved. rights reserved.
Companion Companion Compiling Programs with
Website
Executing Assertions Example Website
Assertions
public class AssertionDemo {
public static void main(String[] args) {
int i; int sum = 0;
Since assert is a new Java keyword introduced in
for (i = 0; i < 10; i++) { JDK 1.4, you have to compile the program using
}
sum += i;
a JDK 1.4 compiler. Furthermore, you need to
assert i == 10; include the switch –source 1.4 in the compiler
}
assert sum > 10 && sum < 5 * 10 : "sum is " + sum;
command as follows:
}
Companion
Website
Running Programs with Companion
Website Using Exception Handling or
Assertions Assertions
By default, the assertions are disabled at runtime. To Assertion should not be used to replace exception
enable it, use the switch –enableassertions, or –ea for handling. Exception handling deals with unusual
short, as follows: circumstances during program execution. Assertions are
to assure the correctness of the program. Exception
java –ea AssertionDemo
handling addresses robustness and assertion addresses
Assertions can be selectively enabled or disabled at correctness. Like exception handling, assertions are not
class level or package level. The disable switch is – used for normal tests, but for internal consistency and
disableassertions or –da for short. For example, the validity checks. Assertions are checked at runtime and
following command enables assertions in package can be turned on or off at startup time.
package1 and disables assertions in class Class1.
java –ea:package1 –da:Class1 AssertionDemo
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
47 48
rights reserved. rights reserved.
Companion
Website Using Exception Handling or Companion
Website Using Exception Handling or
Assertions, cont. Assertions, cont.
Do not use assertions for argument checking in public Use assertions to reaffirm assumptions. This gives you
methods. Valid arguments that may be passed to a public more confidence to assure correctness of the program. A
method are considered to be part of the method’s common use of assertions is to replace assumptions with
contract. The contract must always be obeyed whether
assertions in the code.
assertions are enabled or disabled. For example, the
following code in the Circle class should be rewritten
using exception handling.
Companion
Website
Using Exception Handling or The File Class
Assertions, cont. The File class is intended to provide an abstraction that
deals with most of the machine-dependent complexities
Another good use of assertions is place assertions in a
switch statement without a default case. For example, of files and path names in a machine-independent
fashion. The filename is a string. The File class is a
switch (month) { wrapper class for the file name and its directory path.
case 1: ... ; break;
case 2: ... ; break;
...
case 12: ... ; break;
default: assert false : "Invalid month: " + month
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
51 52
rights reserved. rights reserved.
Obtaining file properties and manipulating file
Problem: 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 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
53 54
rights reserved. rights reserved.
the followings new try-with-resources syntax that +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.
automatically closes the files. +close() Clos es th is scanner.
+hasNext(): boolean Returns true if this scanner has another token in its input.
try (declare and create resources) { +next(): String Returns next token as a stri ng.
Use the resource to process the file; +nextByte(): byte Returns next token as a b yte.
+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 d ouble.
+useDelimiter(pattern: St ring): Sets this scanner’s delimiting pattern.
Scanner
WriteDataWithAutoClose Run
ReadData Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
57 58
rights reserved. rights reserved.
ReplaceText Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
59 60
rights reserved. rights reserved.
Reading Data from the Web Case Study: Web Crawler
URL url = new URL("www.google.com/index.html"); This case study develops a program that travels the
Web by following hyperlinks.
After a URL object is created, you can use the
openStream() method defined in the URL class to open an
input stream and use this stream to create a Scanner object
as follows:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
61 62
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
63 64
rights reserved. rights reserved.