Chapter 3 BEEC4814
Chapter 3 BEEC4814
Exception Handling
2
Show runtime error
https://liveexample.pearsonc
mg.com/liang/intro11e/html/ Quotient
Quotient.html
With a method
https://liveexample.pearsonc
QuotientWithMethod
mg.com/liang/intro11e/html
/QuotientWithMethod.html
3
https://liveexample.pearsoncmg.c
om/liang/intro11e/html/Quotient QuotientWithException
WithException.html
4
https://liveexample.pearso InputMismatchExceptionDemo
ncmg.com/liang/intro11e/
html/InputMismatchExcept
ionDemo.html
By handling InputMismatchException, your program will
continuously read an input until it is correct.
5
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
6
System errors are thrown by
JVM and represented in the
Error class. The Error class
ClassNotFoundException
describes internal system
errors. Such errors rarely ArithmeticException
occur. If one does, there is IOException
little you can do beyond Exception NullPointerException
notifying the user and trying
to terminate the program RuntimeException
gracefully. IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
7
Exception describes
errors caused by your
ClassNotFoundException
program and external
circumstances. These ArithmeticException
IOException
errors can be caught
and handled by your Exception NullPointerException
program. RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
8
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
9
RuntimeException, Error and their subclasses are
known as unchecked exceptions. All other
exceptions are known as checked exceptions,
meaning that the compiler forces the programmer
to check and deal with the exceptions.
10
In most cases, unchecked exceptions reflect programming
logic errors that are not recoverable. For example, a
NullPointerException is thrown if you access an object
through a reference variable before an object is assigned
to it; an IndexOutOfBoundsException is thrown if you
access an element in an array outside the bounds of the
array. These are the logic errors that should be corrected
in the program. Unchecked exceptions can occur
anywhere in the program. To avoid cumbersome overuse
of try-catch blocks, Java does not mandate you to write
code to catch unchecked exceptions.
11
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
12
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; }
} }
}
13
Every method must state the types of checked
exceptions it might throw. This is known as declaring
exceptions.
14
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. Here is
an example,
15
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
16
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
17
An exception
is thrown in
try try try method3
Call Stack
method3
method2 method2
18
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or
RuntimeException), you must invoke it in a try-catch block or declare to
throw the exception in the calling method. For example, suppose that
method p1 invokes method p2 and p2 may throw a checked exception (e.g.,
IOException), you have to write the code as shown in (a) or (b).
(a) (b)
19
• Objective: This example demonstrates
declaring, throwing, and catching exceptions
by modifying the setRadius method in the
Circle class. The new setRadius method
throws an exception if radius is negative.
TestCircleWithException CircleWithException
https://liveexample.pearsoncmg.com/li https://liveexample.pearsoncmg.com/li
ang/intro11e/html/TestCircleWithExce ang/intro11e/html/CircleWithExceptio
ption.html n.html
20
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}
21
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
22
Suppose no exceptions in
the statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
23
The final block is always
executed
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
24
Next statement in the
method is executed
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
25
try { Suppose an exception of type
Exception1 is thrown in
statement1; statement2
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
26
try { The exception is handled.
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
27
try { The final block is always
executed.
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
28
try { The next statement in the
method is now executed.
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
29
try {
statement1; statement2 throws an
statement2; exception of type Exception2.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
30
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
31
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
32
try {
statement1; Rethrow the exception and
statement2; control is transferred to the
statement3; caller
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
33
• An exception occurs in a method. If you want the
exception to be processed by its caller, you should
create an exception object and throw it. If you can
handle the exception in the method where it occurs,
there is no need to throw it.
34
When should you use the try-catch block in the code?
You should use it to deal with unexpected error
conditions. Do not use it to deal with simple, expected
situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
35
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
36
Use the exception classes in the API whenever possible.
Define custom exception classes if the predefined
classes are not sufficient.
Define custom exception classes by extending
Exception or a subclass of Exception.
37
In Listing 13.8, the setRadius method 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.
https://liveexample.pearsoncmg.com/liang/i
InvalidRadiusException
ntro11e/html/InvalidRadiusException.html
https://liveexample.pearsoncmg.com/liang/int CircleWithRadiusException
ro11e/html/CircleWithRadiusException.html
https://liveexample.pearsoncmg.com/liang/i TestCircleWithCustomException
ntro11e/html/TestCircleWithCustomExceptio
n.html
38
An assertion is a Java statement that enables
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 errors.
39
An assertion is declared using the new Java keyword
assert in JDK 1.4 as follows:
assert assertion; or
assert assertion : detailMessage;
40
When an assertion statement is executed, Java evaluates the
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,
double, boolean, char, and Object.
For the first assert statement with no detail message, the no-arg
constructor of AssertionError is used. For the second assert
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.
41
public class AssertionDemo {
public static void main(String[] args) {
int i; int sum = 0;
for (i = 0; i < 10; i++) {
sum += i;
}
assert i == 10;
assert sum > 10 && sum < 5 * 10 : "sum is " + sum;
}
}
42
Assertion should not be used to replace exception
handling. Exception handling deals with unusual
circumstances during program execution. Assertions are
used to assure the correctness of the program.
Exception handling addresses robustness and assertion
addresses correctness. Like exception handling,
assertions are not used for normal tests, but for
internal consistency and validity checks. Assertions are
checked at runtime and can be turned on or off at
startup time.
43
Do not use assertions for argument checking in public
methods. Valid arguments that may be passed to a
public method are considered to be part of the
method’s contract. The contract must always be obeyed
whether assertions are enabled or disabled. For
example, the following code should be rewritten using
exception handling as shown in Lines 28-35 in
Circle.java in Listing 13.8.
public void setRadius(double newRadius) {
assert newRadius >= 0;
radius = newRadius;
}
44
Use assertions to reaffirm assumptions. This gives you
more confidence to assure correctness of the program.
A common use of assertions is to replace assumptions
with assertions in the code.
45
Another good use of assertions is place assertions in a
switch statement without a default case. For example,
switch (month) {
case 1: ... ; break;
case 2: ... ; break;
...
case 12: ... ; break;
default: assert false : "Invalid month: " + month
}
46
The File class 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. The filename is a string. The File class is a
wrapper class for the file name and its directory path.
47
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.
https://liveexample.pearsoncmg.com/liang/int
ro11e/html/TestFileClass.html TestFileClass
48
49