Download Understanding Java Exception Handling: Throwing, Categories, and Try-Catch-Finally - Prof. and more Study notes Information Technology in PDF only on Docsity!
Chapter 2:
1. Error Handling
2. Software Testing
3. Program Efficiency
What/how do we care
about a program?
Robustness:
Correctness
Speed (Efficiency)
9/10/2008 ITK 179 1
Things 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.
9/10/2008 ITK 179 2
Exceptions
- Throwing Exceptions is Java’s 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)
In Java, they are classes
9/10/2008 ITK 179 3
Exception throwing
The sequence of calling
The sequence of throwing
exceptions
X
bad thing happens
JVM starts application at
main()
main() calls method a()
method a method b()
method b method c()
method c
exception occurs
If the exception cannot
be handled here, it will
continue to throw back
9/10/2008 ITK 179 4
Generating an ArithmeticException
9 * Compute quotient of numerator / denominator.
10 * Assumes denominator is not 0.
12 public static int computeQuotient(int numerator,
13 int denominator) {
14 return numerator / denominator;
Enter two integers: 8 0
Exception in thread “main” java.lang.ArithmeticException: / by zero
at ExceptionEx.computeQuotient(ExceptionEx.java:14)
stack trace at ExceptionEx.main(ExceptionEx.java: 27 )
9/10/2008 ITK 179 5
Categories of exceptions
- 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 categorization affect compile-time behavior only
These represent some error, not programmer’s fault, but
the programmer can (should) do something about it
They are programmer’s fault, the compiler can’t
do a thing.
9/10/2008 ITK 179 6
Java’s Exception Hierarchy
ArrayIndexOutOfBounds Exception
Unchecked
Checked
Example 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(FileNotFoundException ex) { System. out.println(ex.getMessage()); System. exit(1); }
while (in.hasNextLine()) { String aLine = in.nextLine(); wordNo += aLine.length(); } in.close(); return wordNo; } 9/10/2008 ITK 179 8
Try-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 }
CategoriesCategories
Example of Try-Catch-
Finally Blocks
int[] a = new int[3]; int sum = 0; double q=0; a[0]=0;a[1]=1;a[2]=2; for (int i=0;i<5;i++) try { sum += a[i]; q = a[i]/sum; System. out .println("\nquotient is "+q); } catch (IndexOutOfBoundsException ioobe) { System. out .println("\nThe array is too small!"); } catch (ArithmeticException e) { System. err .printf("\nError:%s\n",e); } finally { System. out .println("Sum is "+sum); System. out .println("All is cool\n"); }*
**Error:java.lang.ArithmeticExcept ion: / by zero Sum is 0 All is cool
quotient is 1. Sum is 1 All is cool
quotient is 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
9/10/2008 ITK 179 10
The programmer can throw Exceptions
e.g., to complain about method’s pre-conditions that are
not met
Example:
setLength( double theLength )
// expects its argument to be greater than 0.
What to do when that precondition isn’t met?
⇒⇒⇒⇒ throw an exception!
9/10/2008 ITK 179 11
Throwing an Exception: Example
- Set the length dimension of this Rectangle.
- @param theLength the new length of this Rectangle;
- must be > 0 ***** @throws IllegalArgumentException if theLength is <= 0. */ public void setLength( double theLength ) { if ( theLength <= 0 ) throw new IllegalArgumentException(“Illegal Rectangle length (“ + theLength + ”): must be > 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.
Document that the method throws an exception
9/10/2008 ITK 179 12
Oracle Examples for Rectangle
Operation Purpose Object State Expected Result Rectangle r1 = new Rectangle() To create a rectangle using the default values.
height = 1. length = 1.
A new Rectangle object with default values for the attributes r1.getLength() To verify instantiation and accessor method.
r1.getHeight() To verify instantiation and accessor method.
Operation Purpose Object State Expected Result Rectangle r1 = new Rectangle(2.0, 3.0)
To create a rectangle with client-supplied values.
height = 2. length = 3.
A new Rectangle object with client- supplied values for the attributes r1.getHeight() To verify instantiation and accessor method.
r1.getLength() To verify instantiation and accessor method.
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
9/10/2008 ITK 179 19
Test 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.
9/10/2008 ITK 179 20
Oracle Examples for Rectangle
Operation Purpose Object State Expected Result
Rectangle r1 = new Rectangle(1.0, 2.0) Create a rectangle with client-supplied values
length = 1. height = 2.
A new Rectangle object with client- supplied values for the attributes r1.setLength( 5 ) Test mutator with legal input
length = 5. height = 2. r1.getLength() 5.
Test Case 2.5 Mutator to change a Rectangle’s length: legal input
Operation Purpose Object State Expected Result Rectangle r1 = new Rectangle(1.0, 2.0) Create a rectangle with client-supplied values
length = 1. height = 2.
A new Rectangle object with client- supplied values for the attributes r1.setLength( 0 ) Test mutator with illegal input
IllegalArgument- Exception
Test Case 2.6 Mutator to change a Rectangle’s length: illegal input
You don’t to put 5.0 here
9/10/2008 ITK 179 21
Testing with JUnit
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.
try there
using 3.8 V
JUnit Basics
- TestCase: Super class for JUnit support methods
- Test fixture: instance(s) of the class to be tested
import JUnit.framework.; // JUnit stuff import JUnit.extensions.; // JUnit stuff import gray.adts.shapes.Rectangle; // t he class to test
public class RectangleTester extends TestCase {
private Rectangle r1, r2 ; // test fixture; stores the Rectangle // objects under test
the testing methods we need
9/10/2008 ITK 179 23
JUnit 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
9/10/2008 ITK 179 24
Coding an Oracle as a Method
Test Case 2.1: Verify that instantiation was done properly using default values for the Rectangle’s dimensions. */ public void testInstantiateDefault() { assertEquals ( 1.0, r1.getLength() ); assertEquals ( 1.0, r1.getHeight() ); }
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 } }
setUp() will have been called prior to each test method getting called, creating test object r1 anew for each test
methods provided by JUnit main 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);
}
9/10/2008 ITK 179 26
When 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!
Analysis and Measurement
An algorithm’s 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 algorithm’s input size, we prefer
“smaller” functions
9/10/2008 ITK 179 28
Time Complexity:
Count Instructions
Statements Cost
1 float findAvg1D( int []a, int n ) { 2 float sum = 0; 1
3 int count = 0; 1
4 while ( count < n ) { n + 1 5 sum += grades[count]; n
6 count++; n
7 } 8 if ( n > 0 ) 1
9 return sum / n; 10 else 1
11 return 0.0f;
12 } TOTAL 3 n + 5
How many times
will each instruction
execute?
9/10/2008 ITK 179 29
asymptotic approach
for (int i=0; i< n; i++) { .......... for (int j=i; j< n; j++) { ............ } ......... }
n+(n-1)+(n-2)+......+3+2+
= n(n+1)/
= (½)(n
+n)
n
9/10/2008 ITK 179 30
Big-Oh ( ΟΟΟΟ ) Notation
f ( n ) is Ο( g ( n )) if there are positive constants c and n 0 such
that
f ( n ) ≤ cg ( n ), for all n ≥ n 0.
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 ).
9/10/2008 ITK 179 37
Linear Search
Statements Cost
1 int linearSearch( int [] a, int n, int target ) {
2 int i = 0; (^1)
3 while ( i < n ) { n + 1
4 if ( target == a[i] ) n
5 return i; (^1)
6 i++; n
7 }
8 return –1; 1
9 }
TOTAL 3 n + 3
9/10/2008 ITK 179 38
Big-Oh ( ΟΟΟΟ ): Linear Search
TlinearSearch( n ) = 3 n + 3 = Ο( n ) for c = 4 and n 0 = 0,
in the worst case.
4 n
n^2
3 n + 3
TlinearSearch( n ) = Ο( n
But this is an abuse of
O-notation
9/10/2008 ITK 179 39
Constant Time Algorithms: O(1)
int medianOf3( int []a, int n ) {
int v1 = a[0];
int v2 = a[n/2];
int v3 = a[n-1];
if ( (v1 < v2 ) && ( v1 < v3 ) ) // v1 is smallest
if ( v2 < v3 )
return n/2; // middle position
else return n - 1; // last position
else if ( ( v2 < v1 ) && ( v2 < v3 ) ) // v2 smallest
if ( v1 < v3 )
return 0; // first position
else return n – 1; // last position
else // v3 is smallest
if ( v1 < v2 )
return 0; // first position
else return n / 2; // middle position
O(1): the number of instructions
executing is independent of
the size of the input
9/10/2008 ITK 179 40
Some Common Computing Times
log 2 n n n log 2 n n^2 2 n
6 64 384 4,096 1.84 × 1019
7 128 896 16,384 3.40 × 1038
8 256 2,048 65,536 1.16 × 1077
9 512 4,608 262,144 1.34 × 10154
10 1,024 10,240 1,048,576 1.80 × 10308
9/10/2008 ITK 179 41
Algorithm Measurement
Asymptotic analysis doesn’t 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
9/10/2008 ITK 179 42
Algorithm 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
9/10/2008 ITK 179 43
Algorithm Measurement: A Code Fragment
// allocate & initialize int array with values from SIZE - 1 to 0 intArray = new int[SIZE]; for ( int j = 0, i = SIZE - 1; i >= 0; j++, i-- ) intArray[j] = i;
// find the largest value in the int array for ( int i = 0; i < NUM_ITERATIONS; i++ ) { int largest = intArray[0]; start = System.currentTimeMillis(); for ( int j = 1; j < SIZE; j++ ) if ( intArray[j] > largest ) largest = intArray[j]; 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
9/10/2008 ITK 179 44
Some Astonishing Results?
n array of int array of Integer
Timings for findMax() on an array of ints and an
array of Integers (times are in milliseconds)
9/10/2008 ITK 179 45