Title: Chapter 2: 1' Error Handling 2' Software Testing 3' Program Efficiency
1Chapter 2 1. Error Handling 2. Software
Testing 3. Program Efficiency
What/how do we care about a program?
?Correctness
? Speed (Efficiency)
2Things that can go wrong
- Logic error The program is incorrect ?
- Environment error - e.g. out of memory
- I/O error e.g., lost network connection.
3Exceptions
In Java, they are classes
- Throwing Exceptions is Javas way of telling you
something has gone wrong - When an exceptional condition occurs, an
exception object is created storing information
about the nature of the exception (kind, where it
occurred, etc.). When this happens, we say that
an exception is thrown. - The JVM looks for a block of code to catch and
handle the exception (do something with it)
4Exception throwing
bad thing happens
The sequence of throwing exceptions
method c ? exception occurs
X
If the exception cannot be handled here, it will
continue to throw back
method b ? method c()
method a ? method b()
main() calls ? method a()
JVM starts application at main()
The sequence of calling
5Generating an ArithmeticException
- 8 /
- 9 Compute quotient of numerator /
denominator. - 10 Assumes denominator is not 0.
- 11 /
- 12 public static int computeQuotient(int
numerator, - 13 int
denominator) - 14 return numerator / denominator
- 15
Enter two integers 8 0 Exception in thread
main java.lang.ArithmeticException / by zero
at ExceptionEx.computeQuotient(ExceptionEx.jav
a14) at ExceptionEx.main(ExceptionEx.java2
7)
stack trace
6Categories of exceptions
These categorization affect compile-time behavior
only
- Checked exceptions descended from class
Exception, but outside the hierarchy rooted at
RuntimeException. The compiler will check that
you either catch or re-throw checked exceptions. - Unchecked exceptions (aka Runtime Exception )
represent the kinds of errors your program can
avoid through careful programming and testing.
The compile does not check to see that you handle
these exceptions.
These represent some error, not programmers
fault, but the programmer can (should) do
something about it
They are programmers fault, the compiler
cant do a thing.
7Javas Exception Hierarchy
Unchecked
Checked
8Example of handling a checked exception
public static int countCharsInAFile(String str)
Scanner in null int wordNo 0
try File file new File(str) in new
Scanner(file) catch(FileNotFoundExcepti
on ex) System.out.println(ex.getMessage())
System.exit(1) while
(in.hasNextLine()) String aLine
in.nextLine() wordNo aLine.length()
in.close() return wordNo
9Try-Catch-Finally Blocks
try program statements some of which may
throw an exception catch ( ExceptionType1
exception ) program statements to handle
exceptions of type ExceptionType1 or any of its
subclasses catch ( ExceptionType2 exception )
program statements to handle exceptions of
type ExceptionType2 or any of its subclasses .
. . other catch clauses catch ( ExceptionTypeN
exception ) program statements to handle
exceptions of type ExceptionTypeN or any of its
subclasses finally this block is optional
program statements that execute after the try
block or a catch block has executed this
block will execute whether or not an exception is
thrown
Categories
Categories
10Example of Try-Catch-Finally Blocks
int a new int3 int sum 0 double
q0 a00a11a22 for (int
i0ilt5i) try sum ai q
ai/sum System.out.println("\nquotient is
"q) catch (IndexOutOfBoundsException ioobe)
System.out.println("\nThe array is too
small!") catch (ArithmeticException e)
System.err.printf("\nErrors\n",e) finally
System.out.println("Sum is "sum) System.out.pr
intln("All is cool\n")
Errorjava.lang.ArithmeticException / by
zero Sum is 0 All is cool quotient is
1.0 Sum is 1 All is cool quotient is 0.0 Sum
is 3 All is cool The array is too small! Sum
is 3 All is cool The array is too small! Sum
is 3 All is cool
11The programmer can throw Exceptions
- e.g., to complain about methods pre-conditions
that are not met
Example setLength( double theLength ) //
expects its argument to be greater than 0. What
to do when that precondition isnt met?
? throw an exception!
12Throwing an Exception Example
Document that the method throws an exception
/ Set the length dimension of this
ltttgtRectanglelt/ttgt. _at_param theLength the new
length of this ltttgtRectanglelt/ttgt
must be gt 0 _at_throws IllegalArgumentException
if ltttgttheLengthlt/ttgt is lt 0. / public void
setLength( double theLength ) if ( theLength
lt 0 ) throw new IllegalArgumentException(Il
legal Rectangle length (
theLength ) must be gt 0 )
this.length theLength
Create an exception object the way you create any
other kind of object, with new. Throw the
exception with the reserved word throw.
13- public class HandleExceptions
- public static void main(String args)
- System.out.println("Testing Exception
Handling\n") - try
- int i1,j2
- Exception myExnull
- String s"0.2"
- iInteger.parseInt(s)
- if (i gt j)
- throw new RuntimeException()
- int A new int5
- i1
- if (ilt2 igt4)
- throw new IndexOutOfBoundsExceptio
n() - i 5
- i Ai
-
catch (NumberFormatException ex)
System.out.println("\n"ex.toString())
ex.printStackTrace() catch
(IllegalArgumentException ex)
System.out.println("\n"ex.toString())
ex.printStackTrace() catch
(ArrayIndexOutOfBoundsException ex)
System.out.println("\n"ex.toString())
ex.printStackTrace() catch
(IndexOutOfBoundsException ex)
System.out.println("\n"ex.toString())
ex.printStackTrace() catch
(RuntimeException ex)
System.out.println("\n"ex.toString())
ex.printStackTrace() finally
System.out.println("\nWe are done.
Finally!!")
14Custom Exception Classes
Create a custom unchecked exception class simply
by extending RuntimeException and providing two
constructors. Everything else you need is
inherited from Throwable!
package gray.adts.shapes / The exception
that is thrown whenever an operation on a
shape is in violation of a method pre-condition.
/ public class ShapeException extends
RuntimeException public ShapeException()
super() public ShapeException(
String errMsg ) super( errMsg )
extends Exception for unchecked
15How do I know my program is correct?
Not a good answer?
I feel like it is correct!
- Theoretical approach
- Experimental approach
-
Formal proof Program correctness proof Automatic
proving system Heavy mathematics, but very precise
Test the program thoroughly We need a sound test
plan Heuristic, not precise, but doable
16Software Testing
- You should test throughout the software
development cycle, namely, every stages - After the analysis and design are complete
- During the implementation (test driven
development) (Write a little, test a little) - After the implementation is complete
17Check the Specifications
- Verify that the ADTs API contains all the
operations clients will need and that the names
are consistent and meaningful - Verify that the specification is internally
consistent. Ensure operation pre- and
post-conditions are not in conflict with ADT
invariants - Design a test plan based on the behavior
described in the ADT
18Unit and Black-box Testing
- Treat a class and its methods as black boxes
- For a given input you know what should be output
by the box, but you dont how it was generated - An Oracle (test case) predicts what should be
produced. It consists of four columns
Format for an oracle
For each row, we have
19Oracle Examples for Rectangle
Test Case 2.1 Instantiation of a Rectangle object
using default values for the attributes
Test Case 2.2 Instantiation of a Rectangle object
using legal, client-supplied values
20Test During the implementation, Clear-box Testing
- Use oracles tests based on what is known about
the implementation
For example Path coverage test all possible
paths through the code .
21Oracle Examples for Rectangle
Test Case 2.5 Mutator to change a Rectangles
length legal input
You dont to put 5.0 here
Test Case 2.6 Mutator to change a Rectangles
length illegal input
22Testing with JUnit
try there using 3.8 V
The green bar of happiness all tests passed!
Names of the testing methods corresponding to the
oracles you prepared. A green check mark means
the test passed.
23JUnit Basics
- TestCase Super class for JUnit support methods
- Test fixture instance(s) of the class to be
tested
the testing methods we need
import JUnit.framework. // JUnit
stuff import JUnit.extensions. //
JUnit stuff import gray.adts.shapes.Rectangle
// the class to test public class
RectangleTester extends TestCase private
Rectangle r1, r2 // test fixture stores the
Rectangle //
objects under test
24JUnit Basics setUp() and tearDown()
/ Called AUTOMATICALLY before EACH testXXX()
method is run. / protected void setUp() r1
new Rectangle() r2 new Rectangle( 2.0,
3.0 ) / Called AUTOMATICALLY after EACH
testXXX() method is run. / protected void
tearDown() r1 null r2 null
setUp() // establish the test
fixture testXXX() // run the test tearDown()
// do house cleaning
25Coding an Oracle as a Method
methods provided by JUnit
/ Test Case 2.1 Verify that instantiation was
done properly using default values for the
Rectangles dimensions. / public void
testInstantiateDefault() assertEquals( 1.0,
r1.getLength() ) assertEquals( 1.0,
r1.getHeight() )
setUp() will have been called prior to each
test method getting called, creating test
object r1 anew for each test
/ Test Case 2.6 Verify mutator for length
catches illegal input. / public void
testInstantiateDefault() try
r1.setLength( 0 ) // 0 is illegal exception
should be thrown fail( Should raise
IllegalArgumentException) catch (
IllegalArgumentException e )
assertTrue(true) // expected an exception, so
the test passes
26main method in the tester
public static void main (String args)
// Use Java's reflection mechanism to get the
name of // this class. String
TestCaseName RectangleTester.class.getName()
junit.swingui.TestRunner.main
(TestCaseName)
27When a Test Fails
The red bar of sadness some tests failed
Names of the testing methods corresponding to the
oracles you prepared. A red X means the test
failed.
Stack trace telling what was expected, what was
generated and where the test failed very handy!
28Analysis and Measurement
- An algorithms performance can be described by
its - Time complexity how long it takes to execute.
In general, our preference is for shorter
execution times rather than longer ones - Space complexity how much additional space the
algorithm needs. If the amount of additional
memory needed is a function of the algorithms
input size, we prefer smaller functions
29Time Complexity Count Instructions
How many times will each instruction execute?
30asymptotic approach
n(n-1)(n-2)......321 n(n1)/2 (½)(n2
n)
for (int i0 ilt n i) .......... for
(int ji jlt n j) ............
.........
? n2
31Consider the worst part of the program
if (....) ......... ......... else
......... .........
n2
? n3
n3
32Big-O notation in Algorithm Analysis
for (int i0 ilt n i) ................
................ for (int i0 ilt n i)
.......... for (int j0 jlt n j)
............ for (int k0 kltn k)
........... ......... for
(int i0 ilt n i) .......... for (int
j0 jlt n j) ............
.........
? n
? n3
O(cnn3n2) ? O(n3)
? n2
33Most commonly used Asymptotic notations
There are collections of functions with certain
asymptotic properties. Thus, when we say g is
O(f) we really mean g is in O(f)
34Asymptotic notation
(for all but finitely many)
- Upper bound Big-O notation, O(f)
- g ? O(f) iff ?c ?n0 ?n n n0 ? g(n) ? cf(n)
- Lower bound Big-? notation, ?(f)
- g ? ?(f) iff ?c ?n0 ?n n n0 ? g(n) cf(n)
- Approximation Big-? notation, ?(f)
- g ? ?(f) iff ?c1 ?c2 ?n0 ?n n n0 ? c2f(n)?
g(n)? c2f(n) - equivalently g ? O(f) and g ? ?(f)
- Tied Upper bound Little-o notation, o(f)
- g ? o(f) iff ?c ?n0 ?n n n0 ? g(n) ? cf(n)
35Theta (?) Notation
A function f(n) is in ?(g(n)) if there are
positive constants c1, c2, and n0 such that
0 ? c1g(n) ? f(n) ? c2g(n) for all n ? n0.
This means that for all n ? n0, the graph of
f(n) falls between c1g(n) and c2g(n).
36Theta (?) Example T (n) 3n5
- T (n) ?(n), for c1 2, c2 4, n0 5
4n
3n 5
2n
0 ? 2n ? 3n 5 ? 4n
37Big-Oh (?) Notation
- f(n) is ?(g(n)) if there are positive constants c
and n0 such that - f(n) ? cg(n), for all n ? n0.
- f(n) grows no faster than a multiple of g(n)
- I.e., f(n) is an upper bound on the growth rate
of f(n).
38Linear Search
39Big-Oh (?) Linear Search
TlinearSearch(n) 3n 3 ?(n) for c 4 and n0
0, in the worst case.
n2
TlinearSearch(n) ?(n2) But this is an abuse
of O-notation
4n
3n 3
40Constant Time Algorithms O(1)
O(1) the number of instructions executing is
independent of the size of the input
int medianOf3( int a, int n ) int v1
a0 int v2 an/2 int v3 an-1
if ( (v1 lt v2 ) ( v1 lt v3 ) ) // v1 is
smallest if ( v2 lt v3 ) return n/2
// middle position else return n -
1 // last position else if ( (
v2 lt v1 ) ( v2 lt v3 ) ) // v2 smallest if (
v1 lt v3 ) return 0 //
first position else return n 1
// last position else
// v3 is smallest if ( v1 lt v2 )
return 0 //
first position else return n / 2
// middle position
41Some Common Computing Times
42Algorithm Measurement
Asymptotic analysis doesnt always tell the full
story. Asymptotically, finding the largest value
in an array of ints and an array of Integer
objects is the same, but in reality
Pseudocode for timing an algorithm 1.
initialize the data structure 2. for n
iterations 3. get the starting time 4.
run the algorithm 5. get the finish time 6.
totaltime totaltime ( finish time start
time) 7. average time total time / n
43Algorithm Measurement
- Use System.currentTimeMillis() to get the current
time in milliseconds - Measuring execution time is limited by the
resolution of the clock - System activity can affect timing
- Run the garbage collector before doing a timing
to minimize the likelihood it will run during a
timing
44Algorithm Measurement A Code Fragment
// allocate initialize int array with values
from SIZE - 1 to 0 intArray new intSIZE for
( int j 0, i SIZE - 1 i gt 0 j, i-- )
intArrayj i // find the largest value in
the int array for ( int i 0 i lt
NUM_ITERATIONS i ) int largest
intArray0 start System.currentTimeMillis()
for ( int j 1 j lt SIZE j ) if (
intArrayj gt largest ) largest
intArrayj finish System.currentTimeMillis(
) intArrayTimeTotal finish - start //
force cleanup to prevent it happening while //
looking for the largest in the Integer
array intArray null // make the array
garbage System.gc() // invoke the garbage
collector
Get the start time
Get the finish time
Cleanup between timings
45Some Astonishing Results?
Timings for findMax() on an array of ints and
an array of Integers (times are in milliseconds)