Download Exception

Document related concepts
no text concepts found
Transcript
Lesson 4
Programming Techniques
Exception Handling /EH/
AUBG ICoSCIS Team
Assoc. Prof. Stoyan Bonev
March, 23 - 24, 2013
SWU, Blagoevgrad
Time Schedule
March 23, Saturday – 10:00 – 10:45
– 11:00 – 11:45
– 12:00 – 12:45
Lunch Break (45’)
– 13:30 – 14:15
– 14:30 – 15:15
– 15:30 – 16:15
March 24, Sunday
09:00 – 09:45
10:00 – 10:45
11:00 – 11:45
Lunch Break (45’)
12:30 – 13:15
13:30 – 14:15
14:30 – 15:15
Lecture Contents:
 EH – Theory
 EH – Practice
 Demo Programs
3
EH – Theory
 Obsolete PL are designed/implemented in a way
that user programs can not detect/react with
errors and specific cases. An occurrence of an
error causes the program to terminate and
transfer control back to OS as master caller.
 The typical OS reaction to a run-time error is
to display diagnostic message (meaningful or
highly cryptic) and to terminate the program.
 How to detect errors & attempt to recover
without loss of app control?
4
EH – Theory
 Over years, different mechanisms have evolved
 Old systems non structured approach: error
checking based on if stmt explicit tests of




special RTL function return values or
some auxiliary global variable such as C's errno or
floating point status flags or
input validation to filter exceptional cases
 Structured approach: error checking based on
exceptions and EH techniques
5
EH – Theory
 Exception – any unusual event (erroneous or
not) detectable by hardware or by software
and that may require special processing.
 Exception Handling – a special processing that
may be required by the detection of an
exception.
 Exception Handler – a program code that is
used to do the special processing, i.e. exception
handling.
 Exception is raised when the associated event
occurs.
6
EH – Theory
Attention!
 Next three slides of high importance.
 There is no useless or needless even a word.
 Read carefully in order to understand the EH
philosophy.
7
EH – Theory (after D.Liang)
 Runtime errors or abnormal conditions occur while a program is
running if the environment detects an operation that is
impossible to carry out. For example,
 zero division, index out of range, int overflow, non existing file
 In OOP, runtime errors are caused by exceptions.
 Exception is an object that represents an error or condition
that prevents execution from processing normally.
 If exception is not handled, program terminates abnormally.
 In order to avoid abnormal termination, we need EH.
 In order to explore EH concept, incl. how to create, throw,
catch and handle an exception, we use a syntax construct
that contains try block, catch block(s) & optional finally block.
8
EH – Theory D.Liang
 The try block contains code to execute in normal circumstances.
 The catch block contains code to execute in abnormal
circumstances (e.g. zero divisor). In such an event the program
throws an exception by executing stmt like
throw new ArithException(“zero division”);
 The value thrown AE(“zero division”) is called an exception.
 The execution of a throw stmt is called throwing an exception.
 The exception is an object created from an Exception class.
 When an exception is thrown, normal execution flow interrupts
 The exception is passed from try block and caught by catch blk
 The code in the catch block is executed to handle the exception
 Afterward, stmt after the catch block is executed
9
EH – Theory D.Liang
 The throw stmt is analogous to method call, but instead of
calling a method, it calls a catch block.
 In this sense, catch block is like a method definition with a
parameter that matches the type of the value being thrown.
 Unlike a method, after the catch block terminates, the control
does not return to follow the throw stmt,
 Instead it executes the next stmt after the catch block.
10
EH – Theory D.Liang
 In summary, the try…catch blocks template may look like this:;
try {
Code to try;
Throw an exception with throw stmt or from method;
More code to try;
}
catch (type ex) {
Code to process the exception;
}
 An exception may be thrown directly by using a throw stmt in a
try block, or by invoking a method that may throw exception
 An exception may be thrown explicitly (throw stmt typed by
developer) or implicitly (invoked by the environment)
11
EH – Advantages D.Liang
Problem: compute quotient using a method
The main method invokes quotient(…) method
If the method operates normal data, it returns a value to caller
If the method encounters error (zero divisor), it throws the
exception back to its caller.
 The caller’s catch block handles the exception.
 EH advantages: EH enables a method to throw an exception to
its caller. The caller can handle the exception. Without EH, the
called method itself must handle the exception or terminate
program. Often the called method does not know what to do in
case of an error (RTL functions). The library method detects
the error, but only the caller knows what needs to be done when
an error occurs.




12
EH – Advantages D.Liang
 The moral: The essential benefit of
EH is to separate the detection of
an error (done in called method) from
the handling of an error (done in the
caller method).
13
Advantages of having EH
 Without EH the code required to detect errors can
considerably clutter the program.
 Exception propagation. It allows an exception
raised in one program unit to be handled in some
other unit, i.e. a single EHandler to be reused for a
large number of different program units.
 A PL that supports EH encourages its users to
consider all the events that could occur during
program execution and how they can be handled
 This results to solid and reliable code.
5/24/2017
Assoc. Prof. Stoyan Bonev
14
EH – Practice in Java
// file quotient1_NakedCode.java.
//Pure, naked, risky assignment statement
quotient = dividend / divisor;
 Run program with regular data and wrong data
15
EH – Practice in Java
// file quotient2_WithIF.java
//Simple way to fix the problem is to add if stmt
// to test the divisor
if (divisor != 0) {
quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " is = " + quotient);
}
else
System.out.println("Divisor cannot be zero ");
 Run program with regular data and wrong data
16
EH – Practice in Java
// file quotient3_WithExplicitThrownException.java
//Explicitly written code to throw an exception
...
try {
…
if (divisor == 0) throw new ArithmeticException("Divisor cannot be zero ");
quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " is = " + quotient);
} // end of try
catch (ArithmeticException ae) {
System.out.println(" Exception: an integer cannot be divided by zero ");
System.out.println(ae.getMessage());
ae.printStackTrace(); // print call stack
}
finally {
System.out.println("\n\n Finally block executed");
17
}
.. .
EH – Practice in Java
// file quotient4_WithImplicitThrownException.java
//Implicitly written code to throw an exception
//Run-time system creates exception and throws it
...
try {
…
quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " is = " + quotient);
} // end of try
catch (ArithmeticException ae) {
System.out.println(" Exception: an integer cannot be divided by zero ");
System.out.println(ae.getMessage());
ae.printStackTrace(); // print call stack
}
finally {
System.out.println("\n Finally block executed");
}
18
EH – Zero Division in Java
// file quotient5_WithMethodJAVA.java
//Exception explicitly/implicitly raised in one method
//Exception caught in another method
public static int quotient(int num1, int num2) throws ArithmeticException {
if (num2 == 0)
throw new ArithmeticException("Divisor cannot be zero ");
return num1/num2;
}
public static void main(String[] args) {
try {
result = quotient(dividend, divisor);
System.out.println(dividend + " / " + divisor + " is = " + result);
} // end of try
catch (ArithmeticException ae) {
System.out.println(" Exception: an integer cannot be divided by zero ");
System.out.println(ae.getMessage());
ae.printStackTrace(); // print call stack
}
19
} // end of main
EH – noncompatible input data
typed in Java
// file Demo1MismatschExceptionJAVA.java
//Exception InputMismatchException implicitly raised
if when cin.nextInt() method invoked, the input entered
is not an integer
//Exception caught




Open the file
Go over it
Build the app
Run program with regular data and wrong data
20
EH – registering nonexisting
file in Java
// file DemoFileNotFoundException.java
//Exception FileNotFoundException implicitly raised if
when invoking Scanner(File file) constructor, and the file
specified does not exist
//Exception caught




Open the file
Go over it
Build the app
Run program with regular data and wrong data
21
EH – Practice in Java
// File CircleWithException.java
// File CircleWithUserException.java
22
EH – Instead of Conclusion
 There are a couple of exception handling styles in use.
 In the most popular style, an exception is initiated by a special
statement (throw, or raise) with an exception object aargument.
 The scope for exception handlers starts with a marker clause
(try) and ends in the start of the first handler clause (catch,
except, rescue).
 Several handler clauses can follow, and each can specify which
exception types it handles and what name it uses for the
exception object.
 There is a related clause (finally, or ensure), that is executed
whether an exception occurred or not, typically to release
resources acquired within the body of the exception-handling
block.

In its whole, exception handling code might look like this (in Javalike pseudocode; note that an exception type called
EmptyLineException would need to be declared somewhere):23
EH – Instead of Conclusion
try {
line = console.readLine();
if (line.length() == 0) {
throw new EmptyLineException("The line read from console was empty!");
}
console.printLine("Hello %s!" % line);
console.printLine("The program ran successfully");
} // end of try
catch (EmptyLineException e) {
console.printLine("Hello!");
} // end of catch 1
catch (Exception e) {
console.printLine("Error: " + e.message());
} // end of catch 2
finally {
console.printLine("The program terminates now");
24
}
More on EH
T
25
Part 1
brief introductin to Exception Handling
Exceptions
An exception is an event that disrupts
normal program flow.
26
Three approaches to error checking
1.
Ignore all but the most important errors.

The code is cleaner, but the program will misbehave when it encounters an unusual error.
2.
Do something appropriate for every error.

The code is cluttered, but the program works better.

You might still forget some error conditions.
3.
Do the normal processing in one place, handle the errors in another (this is the Java and C# way).

The code is at least reasonably uncluttered.
27
Java and C# approach:
When an error occurs within a method (e.g. divide by zero;
array index out of bounds; etc.), the method creates an object
and hands it off to the runtime system.
The object, called an exception object, contains information
about the error, including its type and the state of the program
when the error occurred.
Creating an exception object and handing it to the runtime
system is called throwing an exception.
28
After a method throws an exception, the runtime system
attempts to find some code to handle it.
The set of possible code to handle the exception is the ordered
list of methods that had been called to get to the method where
the error occurred.
The list of methods is known as the call stack
The call stack.
29
The runtime system searches the call stack for a method that
contains a block of code that can handle the exception.
This block of code is called an exception handler.
The search begins with the method in which the error occurred
and proceeds through the call stack in the reverse order in
which the methods were called.
When an appropriate handler is found, the runtime system
passes the exception to the handler.
An exception handler is considered appropriate if the type of
the exception object thrown matches the type that can be
handled by the handler.
30
The exception handler chosen is said to catch the exception.
If the runtime system exhaustively searches all the methods on
the call stack without finding an appropriate exception handler,
the runtime system (and, consequently, the program)
terminates.
31
A few kinds of Exceptions
• IOException: a problem doing input/output
– FileNotFoundException: no such file
– EOFException: tried to read past the End Of File
• NullPointerException: tried to use an object that was
actually null (this is a RuntimeException)
• NumberFormatException: tried to convert a non-numeric
String to a number (this is another RuntimeException)
• OutOfMemoryError: the program has used all available
memory (this is an Error)
32
The try statement
• Java provides a control structure, the try statement (also
called the try-catch statement) to separate “normal” code
from error handling:
try {
do the “normal” code, ignoring possible
exceptions
}
catch (some exception) {
handle the exception
}
catch (some other exception) {
handle the exception
}
33
How to use the try statement
• Put try {...} around any code that might throw an
exception
• For each Exception that might be thrown, you must provide
a catch block:
catch (exception_type name) {...}
– You can have as many catch blocks as you need.
– name is a formal parameter that holds the exception
object.
– You can send messages to this object and access its
fields.
34
Example
try
{
result = numerator / denominator;
validResult = true;
}
catch (ArithmeticException e)
{
validResult = false;
}
35
The finally Clause
Optional last clause in a try block.
Will always be executed, no matter whether exceptions have
been thrown and handled.
Will even execute when return is used in a try block.
Usually used to do some final “tidying up” and
“housekeeping”.
finally {
...
}
36
try {
do the “normal” code, ignoring
possible
exceptions
}
catch (some exception) {
handle the exception
}
finally {
...
}
37
Catching an Exception
try {
// normal code here!
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace(); // print call stack
}
 getMessage() is a method of the Throwable class that returns the
error message describing the exception.
 printStackTrace() is also a method of the Throwable class
38
What to do about Exceptions
• You can catch exceptions with a try-catch statement
– When you catch an exception, you can try to repair the
problem, or you can just print out information about what
happened.
• You can “pass the buck” by stating that the method in which
the exception occurs “throws” the exception
– Example:
void openFile(String fileName) throws
IOException {
...
}
• Which of these you do depends on whose responsibility it is
to do something about the exception
– If the method “knows” what to do, it should do it
– If it should really be up to the user (the caller of the method
39
in which the exception occurs ) to decide what to do, then
Methods that Throw
public double divide (int dividend, int divisor) throws
ArithmeticException {
if (divisor == 0) {
throw new ArithmeticException(“Divide by 0 error”);
}
return dividend / divisor;
}
 Mark what it throws in method signature.
 Throwing is a little bit like returning, ends method right
away.
 Now up to calling method to catch exception.
40
Stack Trace?
public class TestException {
public static void main(String[] args) {
try {
Running it prints this:
danger1();
}
java.lang.Exception: Danger!
catch(Exception e) {
at Exceptions.danger3(Exceptions.java:31)
e.printStackTrace();
at Exceptions.danger2(Exceptions.java:27)
}
at Exceptions.danger1(Exceptions.java:23)
}
at Exceptions.main(Exceptions.java:15)
public static void danger1() throws Exception {
danger2();
}
public static void danger2() throws Exception {
danger3();
}
}
public static void danger3() throws Exception {
throw new Exception("Danger!");
}
41
Multiple catch Statements
try {
// normal code here!
}
catch(ArithmeticException e) {
// Specific error handling here
}
Order Matters!
Less general
first!
catch(AnotherException e) {
// More general error handling here
}
42
Part 2
Exception Handling
in Details
43
Introduction
When a program runs into a runtime error, the program
terminates abnormally.
In Java, runtime errors are caused by exceptions.
An exception is an object that represents an error or an
abnormal condition.
If the exception is not handled, the program will terminate
abnormally.
How can you handle the runtime error so that the program can
continue to run or terminate gracefully? This is the Exception
Handling subject.
44
Exception-Handling Overview
 To demonstrate EH, including how an exception
object is created and thrown:
 Open Quotient.java that reads two integers and
displays their quotient.
 Run program with regular data
 Run program with illegal data (integer zero div)
 FYI: FP real value divided by zero does not raise an
exception.
45
Exception-Handling Overview
 Pure, naked, risky assignment statement
 quotient = dividend / divisor;
46
Exception-Handling Overview
 Simple way to fix the problem is to add if stmt to test
the divisor:
 Open QuotientWithIf.java that reads two
integers and displays their quotient.
 Run program with regular data
 Run program with illegal data (integer zero div)
47
Exception-Handling Overview
 User specified if statement
if (divisor != 0) {
quotient = dividend / divisor;
System.out.println(dividend+" / "+divisor+" is = "+quotient);
}
else
System.out.println("Divisor cannot be zero ");
48
Exception-Handling Overview
 To demonstrate EH, including how to create, throw,
catch and handle an exception object:
 Open QuotientWithExcepionVerLiang.java that
reads two integers and displays their quotient.
 Run program with regular data
 Run program with illegal data (integer zero div)
49
Exception-Handling Overview
 Explicitly written code to throw an exception
 try {
…
if (divisor == 0)
throw new ArithmeticException("Divisor cannot be zero ");

quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " is = " + quotient);
} // end of try
catch (ArithmeticException aeRef) {
System.out.println(" Exception: integer cannot divide by zero ");
System.out.println(aeRef.getMessage());
aeRef.printStackTrace(); // print call stack
}
catch (InputMismatchException imeRef) {
System.out.println(" Exception " + imeRef.toString() );
}
finally {
System.out.println("\n\n Finally block executed");
}
50
Exception-Handling Overview
 To demonstrate EH, including how to create, throw,
catch and handle an exception object:
 Open QuotientWithExcepionVerMalik.java that
reads two integers and displays their quotient.
 Run program with regular data
 Run program with illegal data (integer zero div)
51
Exception-Handling Overview
 No explicit code to throw an exception
 Run-time system creates exception and throws it
 try {
…
quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " is = " + quotient);
} // end of try
 catch (ArithmeticException aeRef) {
System.out.println(" Exception: integer cannot divide by zero ");
System.out.println(aeRef.getMessage());
aeRef.printStackTrace(); // print call stack
}
catch (InputMismatchException imeRef) {
System.out.println(" Exception " + imeRef.toString() );
}
finally {
System.out.println("\n\n Finally block executed");
}
52
Exception-Handling Advantages
To
demonstrate EH advantages:
Open QuotientWithMethod.java that reads two
integers and displays their quotient.
Run program with regular data
Run program with illegal data (integer zero div)
 Now you see the advantages of using EH. It enables a
method to throw an exception (implicitly or explicitly) to its
caller. Without this capability, a method must handle the
exception or terminate the program.
53
Exception-Handling Advantages
Exception
explicitly raised in one method
Exception caught in another method
public static int quotient(int num1, int num2) throws ArithmeticException {
if (num2 == 0)
throw new ArithmeticException("Divisor cannot be zero ");
return num1/num2;
}
public static void main(String[] args) {
try {
result = quotient(dividend, divisor);
System.out.println(dividend + " / " + divisor + " is = " + result);
} // end of try
catch (ArithmeticException aeRef) {
System.out.println(" Exception: an integer cannot be divided by zero ");
System.out.println(aeRef.getMessage());
aeRef.printStackTrace(); // print call stack
}
catch (InputMismatchException imeRef) {
System.out.println(" Exception " + imeRef.toString() );
}
54
Exception-Handling Advantages
Exception
implicitly raised in one method
Exception caught in another method
public static int quotient(int num1, int num2) throws ArithmeticException {
// if (num2 == 0)
//
throw new ArithmeticException("Divisor cannot be zero ");
return num1/num2;
}
public static void main(String[] args) {
try {
result = quotient(dividend, divisor);
System.out.println(dividend + " / " + divisor + " is = " + result);
} // end of try
catch (ArithmeticException aeRef) {
System.out.println(" Exception: an integer cannot be divided by zero ");
System.out.println(aeRef.getMessage());
aeRef.printStackTrace(); // print call stack
}
catch (InputMismatchException imeRef) {
System.out.println(" Exception " + imeRef.toString() );
}
55
Handling InputMismatchException
Open DemoMismatchException.java that reads
correctly input stream of integers.
By handling InputMismatchException, your program
will continuously read an input until it is correct.
56
Handling FileNotFoundException
Open DemoFileNotFoundException.java that
raises an exception in case of file not found.
57
58
The class Throwable has two direct subclasses, Exception
and Error.
Exceptions (members of the Exception family) are thrown to
signal abnormal conditions that can often be handled by some
code, though some may not be caught.
Errors (members of the Error family) are usually thrown for
more serious problems, such as OutOfMemoryError, that may
not be so easy to handle.
In general, code you write should throw only exceptions, not
errors.
Errors are usually thrown by the methods of the Java API, or by
the Java Virtual Machine itself.
59
Declaring, Throwing, and Catching
Exceptions
Java’s EH model is based on three operations:
declaring an exception
throwing an exception
catching an exception
declare exception
method1() {
method2() throws Exception {
try {
invoke method2;
}
catch (Exception ex) {
Process exception;
}
catch exception
}
if (an error occurs) {
throw new Exception();
}
}
60
throw exception
Declaring Exceptions
Every method must state the types of checked
exceptions it might throw. This is known as declaring
exceptions.
public void myMethod() throws IOException
public void myMethod()
throws IOException, OtherException
61
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. Here is an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
62
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
63
Catching Exceptions
When an exception is thrown, it can be caught and handled in a try-catch block as follows:
try {// Statements that may throw exceptions
statements;
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVarN) {
handler for exceptionN;
64
}
Catching Exceptions pp465
try
try
try
catch
catch
catch
An exception
is thrown in
method3
Call Stack
method3
main method
method2
method2
method1
method1
method1
main method
main method
main method
65
Catch or Declare Checked Exceptions
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).
void p1() {
try {
p2();
}
catch (IOException ex) {
...
}
}
void p1() throws IOException {
p2();
}
(a)
(b)
66
Example: Declaring, Throwing, and
Catching Exceptions
 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.
 Open CircleWithException.java file
TestCircleWithException
CircleWithException
67
E.g.: Declaring, Throwing, and Catching Exceptions
class Circle {
…
// methods mutators
public void setRadius(double par) throws IllegalArgumentException {
if (par >= 0.0) radius = par;
else throw new IllegalArgumentException("Radius cannot be negative");
}
…
} // end of class Circle
public class CircleWithException {
public static void main(String[] args) {
try {
Circle a = new Circle();
Circle b = new Circle(5.);
Circle c = new Circle(-5.);
}
catch (IllegalArgumentException ex){
System.out.println("\n-->>" + ex + "\n-->>");
System.out.println("\n-->>" + ex.getMessage() + "\n-->>");
ex.printStackTrace(); // print call stack
}
finally {
System.out.println("\n Finally block executed");
}
} // end of method main()
} // end of class
68
Defining Custom Exception Classes

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.
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.
Open CircleWithUserException.java file
69
Defining Custom Exception Classes
class IllegalRadiusException extends Exception {
private double rad;
public IllegalRadiusException(double radius) { // constructor
super("Invalid radius " + radius);
rad = radius;
}
public double getRad() { return rad; }
} // end of class IllegalRadiusException
class Circle {
// methods mutators
public void setRadius(double par) throws IllegalRadiusException {
if(par >= 0.0) radius = par;
else throw new IllegalRadiusException(par);
}
} // end of class Circle
public class CircleWithUserException {
public static void main(String[] args) {
try {
Circle a = new Circle(88.); //a.setRadius(-22.);
Circle b = new Circle(5.); // Circle c = new Circle(-5.);
}
catch (IllegalRadiusException ex){
System.out.println("\n-->>\nInvalid radius is " + ex.getRad() + "\n-->>");
}
70
} // end of method main()
try {
// normal code here!
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace(); // print call stack
}
 getMessage() is a method of the Throwable class that returns the
error message describing the exception.
 printStackTrace() is also a method of the Throwable class
71
Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
// perform operations before exits;
throw ex;
}
72
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
73
Cautions When Using Exceptions
 (+) Exception handling separates error-handling
code from normal programming tasks, thus making
programs easier to read and to modify.
 ( ) 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.
74
When to Throw Exceptions
 An exception occurs in a method.
 If you want the exception to be processed by its
direct caller or by a method within the chain of its
callers, 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.
75
When to Use Exceptions?
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");
}
76
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
77
Assertions
 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.
78
Declaring Assertions
An assertion is declared using the new Java keyword assert
in JDK 1.4 as follows:
assert assertion;
or
assert assertion : detailMessage;
where assertion is a Boolean expression and
detailMessage is a primitive-type or an Object value.
79
Executing Assertions
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.
80
Executing Assertions Example
To demonstrate effect of using assert keyword in Java:
Open AssertionDemo.java source file.
Compile and run the demo program.
81
Executing Assertions Example
public class AssertionDemo {
public static void main(String[] args) {
int i; int sum = 0;
for (i = 0; i <=10; i++) {
sum += i;
}
assert i == 12;
assert sum > 10 && sum < 5 * 10 : "sum is " + sum;
}
}
System.out.println("\n\nExecution continues ...");
82
Compiling Programs with
Assertions
Since assert is a new Java keyword introduced in JDK
1.4, you have to compile the program using a JDK 1.4
compiler. Furthermore, you need to include the
switch –source 1.4 in the compiler command as
follows:
javac –source 1.4 AssertionDemo.java
NOTE: If you use JDK 1.5, there is no need to use the
–source 1.4 option in the command.
83
Running Programs with Assertions
By default, the assertions are disabled at runtime. To enable
it, use the switch –enableassertions, or –ea for short, as
follows:
java –ea AssertionDemo
Assertions can be selectively enabled or disabled at class
level or package level. The disable switch is –
disableassertions or –da for short. For example, the following
command enables assertions in package package1 and
disables assertions in class Class1.
java –ea:package1 –da:Class1
AssertionDemo
84
Using Exception Handling or
Assertions
Assertion should not be used to replace exception handling.
Exception handling deals with unusual circumstances during
program execution. Assertions are 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.
85
Using Exception Handling or
Assertions, cont.
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 2835 in Circle.java in Listing 13.8.
public void setRadius(double newRadius) {
assert newRadius >= 0;
radius = newRadius;
}
86
Using Exception Handling or
Assertions, cont.
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.
87
Using Exception Handling or
Assertions, cont.
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
}
Thank You
for
Your attention!
Liang, Introduction to Java
Programming, Eighth Edition, (c) 2011
89