Chapter 2: Error Handling, Software Testing and Program Efficiency

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
Road Map Introduction to object oriented programming. Classes
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Java Software Solutions Foundations of Program Design Sixth Edition
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Low-Level Detailed Design SAD (Soft Arch Design) Mid-level Detailed Design Low-Level Detailed Design Design Finalization Design Document.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
What/how do we care about a program? Robustness Correctness Efficiency (speed, space) 11/2/20151IT 179  Software Testing  Error Handling  Efficiency.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Exceptions and Assertions Chapter 15 – CSCI 1302.
PROGRAMMING TESTING B MODULE 2: SOFTWARE SYSTEMS 22 NOVEMBER 2013.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures in Java: From Abstract Data Types to the Java Collections.
Eighth Lecture Exception Handling in Java
Exceptions: When things go wrong
Chapter 10 – Exception Handling
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Java Programming Language
Chapter 13 Exception Handling
Introduction to Exceptions in Java
Exceptions, Interfaces & Generics
Introduction Exception handling Exception Handles errors
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
CS102 – Exceptions David Davenport Latest: May 2015
Algorithm Analysis CSE 2011 Winter September 2018.
Chapter 12 Exception Handling and Text IO
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
Exceptions 10-Nov-18.
What/how do we care about a program?
EE422C Software Implementation II
Exception Handling Chapter 9.
Advanced Java Programming
Exceptions Handling the unexpected
Topics Introduction to File Input and Output
Java Programming Language
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Program Correctness and Efficiency
Chapter 13 Exception Handling
Chapter 12: Exceptions and Advanced File I/O
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
CMSC 202 Exceptions 2nd Lecture.
Exceptions 25-Apr-19.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Tutorial Exceptions Handling.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
CSC 143 Java Errors and Exceptions.
Exceptions 10-May-19.
Topics Introduction to File Input and Output
Java Basics Exception Handling.
Exceptions 5-Jul-19.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Chapter 2: Error Handling, Software Testing and Program Efficiency Data Structures in Java: From Abstract Data Types to the Java Collections Framework by Simon Gray

Introduction This chapter looks at three characteristics of programs of interest to us robustness: a program’s ability to spot exceptional conditions and deal with them or shutdown gracefully correctness: does the program do what it is “supposed to”? Unit testing is one way to verify expected program behavior efficiency: all programs use resources (time and space, for example); how can we measure efficiency so that we can compare algorithms?

Things that can go wrong Logic error – The program does something unintended and the fault lies with something the programmer did  Environment error - Something goes wrong with the environment within which the program is running; outside programmer’s control I/O error – A source or a destination for data has a problem (e.g., lost network connection). Sometimes you can recover from these problems

Exceptions Exceptions are 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)

Generating an ArithmeticException Fragment of ExceptionEx.java 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.java:14) at ExceptionEx.main(ExceptionEx.java:27) Result of program run: stack trace

When an exception is thrown

Java’s Exception Hierarchy remember, this means extends

Kinds of exceptions Checked exceptions – descended from class Exception, but outside the hierarchy rooted at RuntimeException. The compiler will check that you either catch or rethrow checked exceptions Unchecked exceptions – represent the kinds of errors your program can avoid through careful programming and testing. The compile does not check to see that you catch/handle these exceptions.

Try-Catch-Finally Blocks The first catch block with an ExceptionTypeX that matches the type of the exception thrown in the try-block will execute. The other catch-blocks will be skipped. Then the finally-block executes. 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

Throwing an Exception Good for complaining about method pre-conditions that are not met Example: setLength( double theLength ) in class Rectangle expects its argument to be greater than 0. What to do when that precondition isn’t met?  throw an exception!

Throwing an Exception: Example Document that the method throws an exception /** * Set the length dimension of this <tt>Rectangle</tt>. * @param theLength the new length of this <tt>Rectangle</tt>; * must be > 0 * @throws IllegalArgumentException if <tt>theLength</tt> 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.

Custom 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 );

Software Testing You should “test” throughout the software development cycle: After the analysis and design are complete During the implementation (test driven development) After the implementation is complete

Check the Specification Verify that the ADT’s 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

Unit 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 don’t how it was generated An Oracle (test case) “predicts” what should be produced. It consists of four columns Format for an oracle Operation Purpose Object State Expected Result A call to an operation of the ADT to be tested. The role the operation plays in the test case. The expected state of the test object once the operation is complete. The expected output (if any).

Oracle Examples for Rectangle Test Case 2.1 Instantiation of a Rectangle object using default values for the attributes Operation Purpose Object State Expected Result Rectangle r1 = new Rectangle() To create a rectangle using the default values. height = 1.0 length = 1.0 A new Rectangle object with default values for the attributes r1.getLength() To verify instantiation and accessor method. 1.0 r1.getHeight() Note how the accessor methods are used to verify state set by a constructor or changed by a mutator. Test Case 2.2 Instantiation of a Rectangle object using legal, client-supplied values Operation Purpose Object State Expected Result Rectangle r1 = new Rectangle(2.0, 3.0) To create a rectangle with client-supplied values. height = 2.0 length = 3.0 A new Rectangle object with client-supplied values for the attributes r1.getHeight() To verify instantiation and accessor method. 2.0 r1.getLength() 3.0

Oracle Examples for Rectangle 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.0 height = 2.0 A new Rectangle object with client-supplied values for the attributes r1.setLength( 5 ) Test mutator with legal input length = 5.0 r1.getLength() 5.0 Test Case 2.6 Mutator to change a Rectangle’s length: illegal input Operation Purpose Object State Expected Result Rectangle r1 = new Rectangle(1.0, 2.0) Create a rectangle with client-supplied values length = 1.0 height = 2.0 A new Rectangle object with client-supplied values for the attributes r1.setLength( 0 ) Test mutator with illegal input IllegalArgument-Exception

Clear-box Testing Once the internals of a method are known, additional tests might be suggested. That is, provide additional oracles based on what is known about the implementation Path coverage – test all possible paths through the code (!!)

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.

JUnit Basics TestCase: The class your test class should extend to get the 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; // the class to test public class RectangleTester extends TestCase { private Rectangle r1, r2; // test fixture; stores the Rectangle // objects under test To inherit the testing and test run methods we will need

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; Make sure each test method starts with a clean copy of the test fixture. This is the sequence of calls the JUnit framework does for you automatically for each test method that is invoked. setUp(); // establish the test fixture testXXX(); // run the test tearDown(); // do house cleaning

Coding an Oracle as a JUnit Test Method methods provided by JUnit /** 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() ); } Remember: 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 testMutatorIllegalInput() { 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 }

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

Time Complexity: Count Instructions Statements Cost 1 float findAvg1D( int []a, int n ) { 2 float sum = 0; 3 int count = 0; 4 while ( count < n ) { n + 1 5 sum += grades[count]; n 6 count++; 7 } 8 if ( n > 0 ) 9 return sum / n; 10 else 11 return 0.0f; 12 TOTAL 3n + 5 How many times will each instruction execute?

Theta () Notation A function f(n) is (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).

Theta () Example: findAvg1d() TfindAvg1D(n) = (n), for c1 = 2, c2 = 4, n0 = 5 4n 3n + 5 2n 0  2n  3n + 5  4n

Big-Oh () Notation A function f(n) is (g(n)) if there are positive constants c and n0 such that f(n)  cg(n) for all n  n0. What we are saying is that f(n) will grow no faster than a multiple of g(n); hence g(n) is an upper bound on the growth rate of f(n).

Linear Search Note: Only 1 return statement will execute, Statements Cost 1 int linearSearch( int []a, int n, int target ) { 2 int i = 0; 3 while ( i < n ) { n + 1 4 if ( target == array[i] ) n 5 return i; 6 i++; 7 } 8 return –1; 9 TOTAL 3n + 3 Note: Only 1 return statement will execute, so the total is 3n + 3 and not 3n +4

Big-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

Constant 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 = 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 }

Some Common Computing Times log2n n n log2n n2 2n 1 2 4 8 16 3 24 64 256 65,536 5 32 160 1,024 4,294,967,296 6 384 4,096 1.84  1019 7 128 896 16,384 3.40  1038 2,048 1.16  1077 9 512 4,608 262,144 1.34  10154 10 10,240 1,048,576 1.80  10308

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; totaltime = 0 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

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

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

Some Astonishing Results? array of int array of Integer 4,000,000 11.363 21.739 8,000,000 22.727 42.958 800,000 2.314 4.329 Timings for findMax() on an array of ints and an array of Integers (times are in milliseconds)