Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.

Slides:



Advertisements
Similar presentations
Simulation and Example
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
COMP 121 Week 5: Exceptions and Exception Handling.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
ITEC200 Week02 Program Correctness and Efficiency.
Program Correctness and Efficiency Chapter 2. Chapter 2: Program Correctness and Efficiency2 Chapter Objectives To understand the differences between.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Program Correctness and Efficiency Chapter 2. Chapter Objectives  To understand the differences between the three categories of program errors  To understand.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Introduction to Software Design Chapter 1. Chapter 1: Introduction to Software Design2 Chapter Objectives Intro - Software OOP Inheritance, interfaces,
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Program Correctness and Efficiency Chapter 2 Chapter 2: Program Correctness and Efficiency2 Chapter Objectives To understand the differences between.
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.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
Slides Credit Umair Javed LUMS Web Application Development.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
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.
JavaScript and Ajax (Control Structures) Week 4 Web site:
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
CIS 068 Welcome to CIS 068 ! Lesson 3: Algorithm Correctness And Efficiency.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
SOFTWARE TESTING LECTURE 9. OBSERVATIONS ABOUT TESTING “ Testing is the process of executing a program with the intention of finding errors. ” – Myers.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Exceptions in the Java programming language J. W. Rider.
Testing and Debugging.
Exception Handling Chapter 9.
Chapter 12 Exception Handling
Algorithm Correctness
Program Correctness and Efficiency
Exceptions 10-May-19.
Presentation transcript:

Fall 2007CS 225 Program Correctness and Efficiency Chapter 2

Fall 2007CS 225 Chapter Topics Three categories of program errors Exceptions Testing strategies Assertions and loop invariants To analyze an algorithm’s efficiency –big-O notation

Fall 2007CS 225 Program Defects and “Bugs” A program may be efficient, but is worthless if it produces a wrong answer Defects often appear in software after it is delivered Testing can never demonstrate the complete absence of defects In some situations it is very difficult to test a software product completely in the environment in which it is used Debugging: the process of removing defects

Fall 2007CS 225 Types of Errors Syntax errors Run-time errors Logic errors

Fall 2007CS 225 Syntax Errors Syntax errors are mistakes in the grammar of a language The Java compiler detects syntax errors during compilation and requires you to correct them before successfully compiling the program

Fall 2007CS 225 Run-time Errors or Exceptions Run-time errors –Occur during program execution –Occur when the JVM detects an operation that it knows to be incorrect –Cause the JVM to throw an exception Examples of run-time errors include –Division by zero –Array index out of bounds –Number format and Input mismatch error –Null pointer exceptions

Fall 2007CS 225 Logic Errors A logic error occurs when the programmer or analyst –Made a mistake in the design of a class or method –Implemented an algorithm incorrectly Most logic errors do not cause syntax or run- time errors and are thus difficult to find –Sometimes found through testing –Sometimes found during real-world operation of the program

Fall 2007CS 225 The Exception Class Hierarchy When an exception is thrown, one of the Java exception classes is instantiated Exceptions are defined within a class hierarchy that has the class Throwable as its superclass –Classes Error and Exception are subclasses of Throwable –RuntimeException is a subclass of Exception

Fall 2007CS 225 Throwable Class Throwable is the superclass of all exceptions All exception classes inherit the methods of throwable

Fall 2007CS 225 Throwable Methods String getMessage() returns the detail message void printStackTrace() prints the call stack String toString() returns the name of the Exception followed by the message

Fall 2007CS 225 Checked vs Unchecked Exceptions Two categories of exceptions –Unchecked exception may result from Programmer error Serious external conditions that are unrecoverable –Checked exception May be beyond the control of the programmer Must be addressed in the program

Fall 2007CS 225 Exception Handling When an exception is thrown, the normal sequence of execution is interrupted –Program stops –JVM displays an error message The programmer may override the default behavior by –Enclosing statements in a try block –Processing the exception in a catch block

Fall 2007CS 225 Uncaught Exceptions When an exception occurs that is not caught, the program stops and the JVM displays an error message and a stack trace The stack trace shows the sequence of method calls, starting at the method that threw the exception and ending at main

Fall 2007CS 225 The try-catch-finally Sequence Avoid uncaught exceptions –Write a try-catch sequence to catch an exception –Handle it rather than relying on the JVM Catch block is skipped if all statements within the try block execute without error

Fall 2007CS 225 Error Recovery Exception handling provides the opportunity to –Recover from errors –Report errors Users are a common source of errors; user errors should be recoverable

Fall 2007CS 225 Error Recovery try { /* code */ } catch ( Exception var) { /* recovery */} finally { /* */ } Catch block within the first catch clause having an appropriate exception class executes, others are skipped Compiler displays an error message if it encounters an unreachable catch clause

Fall 2007CS 225 The finally Block When an exception is thrown, the flow of execution is suspended and there is no return to the try block There are situations in which allowing a program to continue after an exception could cause problems The code in the finally block is executed either after the try block is exited or after a catch clause is exited The finally block is optional

Fall 2007CS 225 Throwing Exceptions Instead of catching an exception in a lower-level method, it can be caught and handled by a higher-level method –Declare that the lower-level method may throw a checked exception by adding a throws clause to the method header –Can explicitly throw the exception in the lower-level method, using a throw statement

Fall 2007CS 225 Throwing Exceptions (continued) The throws clause is useful if a higher-level module already contains a catch clause for this exception type Can use a throw statement in a lower-level method to indicate that an error condition has been detected Once the throw statement executes, the lower-level method stops executing immediately

Fall 2007CS 225 Catching Exceptions Example

Fall 2007CS 225 Guidelines You can always avoid handling exceptions by declaring that they are thrown, or throwing them and letting them be handled farther back in the call chain It is usually best to handle the exception instead of passing it along The following are recommended guidelines: If an exception is recoverable in the current method, handle the exception in the current method If a checked exception is likely to be caught in a higher-level method, declare that it can occur using a throws clause It is not necessary to use a throws clause with unchecked exceptions

Fall 2007CS 225 Testing Programs There is no guarantee that a program that is syntax and run-time error free will also be void of logic errors The “best” situation is a logic error that occurs in a part of the program that always executes; otherwise, it may be difficult to find the error The worst kind of logic error is one that occurs in an obscure part of the code (infrequently executed)

Fall 2007CS 225 Sources of Logic Errors Most logic errors arise during the design phase and are the result of an incorrect algorithm Logic errors may also result from typographical errors that do not cause syntax or run-time errors

Fall 2007CS 225 Structured Walkthroughs One form of testing is hand-tracing the algorithm before implementing Structured walkthrough: designer must explain the algorithm to other team members and simulate its execution with other team members looking on

Fall 2007CS 225 Testing Testing: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects after all syntax errors have been removed and the program compiles No amount of testing can guarantee the absence of defects in sufficiently complex programs

Fall 2007CS 225 Types of Testing Unit testing: checking the smallest testable piece of the software (a method or class) Integration testing: testing the interactions among units System testing: testing the program in context Acceptance testing: system testing designed to show that the program meets its functional requirements

Fall 2007CS 225 Approaches to Testing Black-box testing: tests the item based on its interfaces and functional requirements White-box testing: tests the software with the knowledge of its internal structure

Fall 2007CS 225 Preparations for Testing A test plan should be developed early in the design phase –Aspects of a test plan include deciding how the software will be tested, when the tests will occur, who will do the testing, and what test data will be used If the test plan is developed early, testing can take place concurrently with the design and coding A good programmer practices defensive programming and includes code to detect unexpected or invalid data

Fall 2007CS 225 Testing Methods Most of the time, you will test program systems that contain collections of classes, each with several methods Leave a trace of execution by displaying the method name as you enter it Display values of all input parameters upon entry to a method

Fall 2007CS 225 Testing Methods (continued) Display the values of any class attributes that are accessed by this method Display the values of all method outputs after returning from a method Plan for testing as you write each module rather than after the fact

Fall 2007CS 225 Developing the Test Data Test data should be specified during the analysis and design phases for the different levels of testing: unit, integration, and system –You should test both good data and bad data –Check special cases called boundary conditions

Fall 2007CS 225 White- vs. Black-box Testing In black-box testing, we are concerned with the relationship between the unit inputs and outputs –There should be test data to check for all expected inputs as well as unanticipated data In white-box testing, we are concerned with exercising alternative paths through the code –Test data should ensure that all if statement conditions will evaluate to both true and false

Fall 2007CS 225 Why do Testing? Normally testing is done by –The programmer –Other members of the software team who did not code the module being tested –Final users of the software product

Fall 2007CS 225 Who does the Testing? Programmers are often blind to their own oversights Companies also have quality assurance organizations that verify that the testing process is performed correctly In extreme programming, programmers work in pairs where one writes the code and the other writes the tests

Fall 2007CS 225 When to test? Start testing as early as you can –don't wait until the coding is complete It may be difficult to test a method or class that interacts with other methods or classes

Fall 2007CS 225 Stubs A replacement for a method that has not yet been implemented or tested is called a stub A stub has the same header as the method it replaces, but its body only displays a message indicating that the stub was called –It may need a fixed return value

Fall 2007CS 225 Drivers A driver program declares any necessary object instances and variables, assigns values to any of the method’s inputs, calls the method, and displays the values of any outputs returned by the method You can put a main method in a class to serve as the test driver for that class’s methods

Fall 2007CS 225 Assertions and Loop Invariants Assertions: logical statements about a program that are claimed to be true; generally written as a comment Preconditions and postconditions are assertions A loop invariant is an assertion –Helps prove that a loop meets it specification –True before loop begins, at the beginning of each repetition of the loop body, and just after loop exit

Fall 2007CS 225 Assertions and Loop Invariants Example

Fall 2007CS 225 Assertions in Java Java has an assert statement which can take two forms 1.assert ; Results in an AssertionError if the boolean expression is ever false 2.assert : ; The expression is printed as part of the AssertionError message.

Fall 2007CS 225 Using Assertions in Java Activate assertion checking with a command-line option to the interpreter java -ae

Fall 2007CS 225 Efficiency of Algorithms Can characterize a program by how the execution time or memory requirements increase as a function of increasing input size –Big-O notation A simple way to determine the big-O of an algorithm or program is to look at the loops and to see whether the loops are nested

Fall 2007CS 225 Algorithm Efficiency Consider: First time through outer loop, inner loop is executed n-1 times; next time n-2, and the last time once. So we have –T(n) = 3(n – 1) + 3(n – 2) + … + 3 or –T(n) = 3(n – 1 + n – 2 + … + 1)

Fall 2007CS 225 Algorithm Efficiency We can reduce the expression in parentheses to: –n x (n – 1) / 2 So, T(n) = 1.5n 2 – 1.5n This polynomial is zero when n is 1. For values greater than 1, 1.5n 2 is always greater than 1.5n 2 – 1.5n Therefore, we can use 1 for n 0 and 1.5 for c to conclude that T(n) is O(n 2 )

Fall 2007CS 225 Efficiency of Algorithms