Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures in Java: From Abstract Data Types to the Java Collections.

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

Yoshi
Written by: Dr. JJ Shepherd
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
CS102--Object Oriented Programming
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exception Handling Xiaoliang Wang, Darren Freeman, George Blank.
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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
Introduction to Analysis of Algorithms
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
CS203 Java Object Oriented Programming Errors and Exception Handling.
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.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Low-Level Detailed Design SAD (Soft Arch Design) Mid-level Detailed Design Low-Level Detailed Design Design Finalization Design Document.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
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.
Chapter 8-Exception Handling/ Robust Programming.
Written by: Dr. JJ Shepherd
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Introduction to Exceptions in Java CS201, SW Development Methods.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Chapter 2: Error Handling, Software Testing and Program Efficiency
Exceptions, Interfaces & Generics
Chapter 3: Using Methods, Classes, and Objects
Chapter 12 Exception Handling and Text IO
What/how do we care about a program?
Exception Handling Chapter 9.
Java Programming Language
Chapter 12 Exception Handling
Chapter 12 Exception Handling and Text IO Part 1
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures in Java: From Abstract Data Types to the Java Collections Framework by Simon Gray Chapter 2: Error Handling, Software Testing and Program Efficiency

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-2 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?

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-3 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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-4 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)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-5 Generating an ArithmeticException 8 /** 9 * Compute quotient of numerator / denominator. 10 * Assumes denominator is not */ 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) Fragment of ExceptionEx.java Result of program run: stack trace

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-6 When an exception is thrown

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-7 Java’s Exception Hierarchy remember, this means extends

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-8 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.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-9 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 } 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.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-10 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!

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-11 Throwing an Exception: Example /** * Set the length dimension of this Rectangle. theLength the new length of this Rectangle ; * must be > 0 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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-12 Custom Exception Classes 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 ); } Create a custom unchecked exception class simply by extending RuntimeException and providing two constructors. Everything else you need is inherited from Throwable !

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-13 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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-14 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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-15 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 OperationPurposeObject 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). Format for an oracle

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-16 Oracle Examples for Rectangle OperationPurposeObject StateExpected 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()To verify instantiation and accessor method. 1.0 OperationPurposeObject StateExpected 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()To verify instantiation and accessor method. 3.0 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 Note how the accessor methods are used to verify state set by a constructor or changed by a mutator.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-17 Oracle Examples for Rectangle OperationPurposeObject StateExpected 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 height = 2.0 r1.getLength()5.0 Test Case 2.5 Mutator to change a Rectangle’s length: legal input OperationPurposeObject StateExpected 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 Test Case 2.6 Mutator to change a Rectangle’s length: illegal input

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-18 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 (!!)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-19 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.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-20 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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-21 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 This is the sequence of calls the JUnit framework does for you automatically for each test method that is invoked. Make sure each test method starts with a clean copy of the test fixture.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-22 Coding an Oracle as a JUnit Test 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 } Remember: setUp() will have been called prior to each test method getting called, creating test object r1 anew for each test methods provided by JUnit

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-23 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!

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-24 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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-25 Time Complexity: Count Instructions StatementsCost 1float findAvg1D( int []a, int n ) { 2 float sum = 0; 1 3 int count = 0; 1 4 while ( count < n ) { n 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 3n + 5 How many times will each instruction execute?

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-26 Theta (  ) Notation A function f(n) is  (g(n)) if there are positive constants c 1, c 2, and n 0 such that 0  c 1 g(n)  f(n)  c 2 g(n) for all n  n 0. This means that for all n  n 0, the graph of f(n) falls between c 1 g(n) and c 2 g(n).

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-27 Theta (  ) Example: findAvg1d() T findAvg1D (n) =  (n), for c 1 = 2, c 2 = 4, n 0 = 5 4n4n 3n + 5 2n2n 0  2n  3n + 5  4n

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-28 Big-Oh (  ) Notation A function 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. 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).

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-29 Linear Search StatementsCost 1int linearSearch( int []a, int n, int target ) { 2 int i = 0; 1 3 while ( i < n ) { n if ( target == array[i] ) n 5 return i; 1 6 i++; n 7 } 8 return –1; 1 9} TOTAL 3n + 3

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-30 Big-Oh (  ): Linear Search T linearSearch (n) = 3n + 3 =  (n) for c = 4 and n 0 = 0, in the worst case. 4n4n n2n2 3n + 3 T linearSearch (n) =  (n 2 ) But this is an abuse of O-notation

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-31 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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-32 Some Common Computing Times log 2 nnn log 2 nn2n2 2n2n , ,0244,294,967, ,  ,  ,04865,  ,608262,  ,02410,2401,048, 

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-33 Algorithm Measurement Asymptotic analysis doesn’t always tell the full story. Asymptotically, finding the largest value in an array of int s 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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-34 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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-35 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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-36 Some Astonishing Results? n array of int array of Integer 4,000, ,000, , Timings for findMax() on an array of int s and an array of Integer s (times are in milliseconds)