Program Correctness and Efficiency. Chapter 2

Similar documents
Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Object Oriented Programming

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Object Oriented Programming. Week 7 Part 1 Exceptions

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Exception-Handling Overview

Java Loose Ends. 11 December 2017 OSU CSE 1

Data Structures. 02 Exception Handling

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

BBM 102 Introduction to Programming II Spring Exceptions

EXCEPTION HANDLING. Summer 2018

Object Oriented Programming Exception Handling

Comp 249 Programming Methodology Chapter 9 Exception Handling

Programming II (CS300)

BBM 102 Introduction to Programming II Spring 2017

Exceptions and assertions

Exception Handling in C++

COMP1008 Exceptions. Runtime Error

Internal Classes and Exceptions

Chapter 13 Exception Handling

CSE 331 Software Design & Implementation

Assertions and Exceptions Lecture 11 Fall 2005

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

ECE 122. Engineering Problem Solving with Java

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Chapter 15 Debugging

Programming II (CS300)

Part 5. Verification and Validation

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Darshan Institute of Engineering & Technology for Diploma Studies

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Correctness and Robustness

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Std 12 Lesson-10 Exception Handling in Java ( 1

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Advanced Flow of Control -- Introduction

Errors and Exceptions

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Exception Handling. Chapter 9

Verification and Validation. Ian Sommerville 2004 Software Engineering, 7th edition. Chapter 22 Slide 1

National University. Faculty of Computer Since and Technology Object Oriented Programming

JAVA CONCEPTS Early Objects

Introduction Unit 4: Input, output and exceptions

Object Oriented Programming

Chapter 7 Control Statements Continued

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Introduction to Problem Solving and Programming in Python.

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

CS 3 Introduction to Software Engineering. 3: Exceptions

Data Structures. Subodh Kumar. Dept of Computer Sc. & Engg. IIT Delhi

CS159. Nathan Sprague

Lecture 15 Software Testing

Exceptions, Case Study-Exception handling in C++.

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Sri Vidya College of Engineering & Technology Question Bank

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CS 215 Software Design Homework 3 Due: February 28, 11:30 PM

COMP 401 EXCEPTIONS. Instructor: Prasun Dewan

Chapter 12 Exception Handling

Chapter 11, Testing. Using UML, Patterns, and Java. Object-Oriented Software Engineering

Chapter 9. Software Testing

CS 221 Review. Mason Vail

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Verification and Validation

Verification and Validation

Regression testing. Whenever you find a bug. Why is this a good idea?

CSCI 261 Computer Science II

In this lab we will practice creating, throwing and handling exceptions.

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

17. Handling Runtime Problems

Repetition and Loop Statements Chapter 5

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Exceptions in Java

Typecasts and Dynamic Dispatch. Dynamic dispatch

Topics in Software Testing

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

Absolute C++ Walter Savitch

Verification and Validation

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Unit 5 - Exception Handling & Multithreaded

Designing Robust Classes

6.Introducing Classes 9. Exceptions

Unit Testing as Hypothesis Testing

Object-Oriented Programming

2IP15 Programming Methods

Java Programming Tutorial 1

Foundations of object orientation

Testing & Debugging TB-1

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Examining the Code. [Reading assignment: Chapter 6, pp ]

Transcription:

Program Correctness and Efficiency Chapter 2

Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you should catch exceptions To become familiar with the Exception hierarchy and the difference between checked and unchecked exceptions To learn how to use the try-catch-finally sequence to catch and process exceptions To understand what it means to throw an exception and how to throw an exception in a method

Chapter Objectives (continued) To understand the different testing strategies and when and how they are performed To learn how to write special methods to test other methods and classes To become familiar with debugging techniques and debugger programs To be introduced to the process of program verification and the use of assertions and loop invariants To understand the meaning of big-o notation and how it is used to analyze an algorithm s efficiency

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: removing defects

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 Some common syntax errors include: Omitting or misplacing braces Performing an incorrect type of operation on a primitive type value Invoking an instance method not defined Not declaring a variable before using it Providing multiple declarations of a variable

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

Run-time Errors or Exceptions (continued)

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

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

The Class Throwable Throwable is the superclass of all exceptions All exception classes inherit the methods of throwable

The Class Throwable (continued)

Checked and Unchecked Exceptions Two categories of exceptions: checked and unchecked Checked exception normally not due to programmer error and is beyond the control of the programmer Unchecked exception may result from Programmer error Serious external conditions that are unrecoverable

Checked and Unchecked Exceptions

Catching and Handling Exceptions When an exception is thrown, the normal sequence of execution is interrupted Default behavior 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

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

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

Handling Exceptions to Recover from Errors Exceptions provide the opportunity to Recover from errors Report errors User error is a common source of error and should be recoverable 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

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

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 throw the exception in the lower-level method, using a throw statement The throws clause is useful if a higher-level module already contains a catch clause for this exception type

Throwing Exceptions (continued) 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

Catching Exceptions Example

Programming Style 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 higherlevel method, declare that it can occur using a throws clause It is not necessary to use a throws clause with unchecked exceptions

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)

Structured Walkthroughs 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 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

Levels and Types of 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 Unit testing: checking the smallest testable piece of the software (a method or class) Integration testing: testing the interactions among units

Levels and Types of Testing (continued) System testing: testing the program in context Acceptance testing: system testing designed to show that the program meets its functional requirements 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

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

Testing Tips for Program Systems Most of the time, you will test program systems that contain collections of classes, each with several methods If a method implements an interface, its specification should document input parameters and expected results Carefully document each method parameter and class attribute using comments as you write the code 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

Testing Tips for Program Systems (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

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

Testing Boundary Conditions When hand-tracing through an algorithm or performing white-box testing, you must exercise all paths Check special cases called boundary conditions

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 Do not rely on programmers for testing as they 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

Stubs It may be difficult to test a method or class that interacts with other methods or classes The replacement of 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

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

Using a Test Framework A test framework is a software product that facilitates writing test cases, organizing the test cases into test suites, running the test suites, and reporting the results A test framework often used for Java products is JUnit, an open-source product that can be used in a stand-alone mode and is available from junit.org

BUGS IMPORTANT NOTICE! YOU PUT EVERY BUG THE PROGRAM YOU WROTE! They DID NOT Crawl In from outside.

LOOK FOR BUGS IN CORNERS Boundary conditions.

Debugging a Program Debugging is the major activity performed by programmers during the testing phase Testing determines if there is an error, debugging determines the cause of it Debugging is like detective work Inspect carefully the information displayed by your program Insert additional diagnostic output statements in the method to determine more information

Using a Debugger Debuggers often are included with IDEs A debugger can execute your program incrementally rather than all at once Single-step execution executes in increments as small as one program statement Breakpoints are used to traverse large portions of code before stopping The actual mechanics of using a debugger depend on the IDE that you are using

Using a Debugger (continued)

Reasoning about Programs: 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

Assertions and Loop Invariants Example

Efficiency of Algorithms Difficult to get a precise measure of the performance of an algorithm or program 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

Efficiency of Algorithms (continued) 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)

Efficiency of Algorithms (continued) 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 )

Efficiency of Algorithms (continued)

Chapter Review Three kinds of defects can occur in programs Syntax errors Run-time errors Logic errors All exceptions in the Exception class hierarchy are derived from a common superclass called Throwable The default behavior for exceptions is for the JVM to catch them by printing an error message and a call stack trace and then terminating the program

Chapter Review (continued) Two categories of exceptions: checked and unchecked A method that can throw a checked exception must either catch it or declare that it is thrown throw statement throws an unchecked exception Program testing is done at several levels starting with the smallest testable piece of a program called a unit Integration testing: once units are individually tested, they can then be tested together System testing: once the whole program is put together, it is tested as a whole

Chapter Review (continued) Acceptance programming involves testing in an operational manner demonstrating its functionality Black-box testing tests the item based on its functional requirements without knowledge of its internal structure White-box testing tests the item using knowledge of its internal structure Test drivers and stubs are tools used in testing Test drivers exercise a method or class Stubs stand in for called methods Big-O notation determines the efficiency of a program