Cs2220: Engineering Software Class 6: Defensive Programming Fall 2010 University of Virginia David Evans.

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

Cs2220: Engineering Software Class 10: Generic Datatypes Fall 2010 University of Virginia David Evans.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
David Evans CS201j: Engineering Software? University of Virginia Computer Science Lecture 2: Java Semantics, Validation.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Chapter 11 Debugging and Handling Exceptions
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Introduction to Programming Lesson 1. Objectives Skills/ConceptsMTA Exam Objectives Understanding Computer Programming Understand computer storage and.
FIT FIT1002 Computer Programming Unit 19 Testing and Debugging.
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.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Cs205: engineering software university of virginia fall 2006 Semantics and Specifying Procedures David Evans
Exceptions COMPSCI 105 S Principles of Computer Science.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Cs205: engineering software university of virginia fall 2006 Validation David Evans
Cs3102: Theory of Computation Class 18: Proving Undecidability Spring 2010 University of Virginia David Evans.
CSE 219 Computer Science III Testing. Testing vs. Debugging Testing: Create and use scenarios which reveal incorrect behaviors –Design of test cases:
The Java Programming Language
Class 14: Object-Oriented Programming Fall 2010 University of Virginia David Evans cs2220: Engineering Software.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
1 Debugging. 2 A Lot of Time is Spent Debugging Programs Debugging. Cyclic process of editing, compiling, and fixing errors. n Always a logical explanation.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Building Java Programs Chapter 15 Lecture 15-2: testing ArrayIntList; pre/post conditions and exceptions reading:
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 9: Designing Exceptionally.
Cs2220: Engineering Software Class 12: Substitution Principle Fall 2010 University of Virginia David Evans.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
Cs205: engineering software university of virginia fall 2006 Programming Exceptionally David Evans
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Introduction to Programming Lesson 1. Algorithms Algorithm refers to a method for solving problems. Common techniques for representing an algorithms:
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 17 – Specifications, error checking & assert.
Debugging and Handling Exceptions
Chapter 10 – Exception Handling
Logger, Assert and Invariants
CSE 374 Programming Concepts & Tools
Testing and Exceptions
Testing Recap Testing can find problems, but cannot prove your program works Since exhaustive testing is impossible, select test cases with maximum likelihood.
Subtyping Rules David Evans cs205: engineering software BlackBear
Programming in Java Assertion.
Lecture 9: Exceptions in Java CS201j: Engineering Software
Exceptions 19-Feb-19.
Exceptions 7-Apr-19.
Go to pollev.com/cse143.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Introduction to Programming
Lecture 13: Subtyping Rules Killer Bear Climber
Java Basics Exception Handling.
Exceptions 5-Jul-19.
Lecture 2: Java Semantics, Validation CS201j: Engineering Software?
Presentation transcript:

cs2220: Engineering Software Class 6: Defensive Programming Fall 2010 University of Virginia David Evans

Menu Recap Validation Hopelessness of both testing and analysis! Defensive Programming

Testing Fishing for Bugs Each test examines one path through the program Exhaustive All possible inputs: infeasible for all non-trivial programs Path-Complete All possible paths through the program

Path-Complete Testing? public static int [] histogram (int [] a) // unspecified { int maxval = 0; for (int i = 0; i < a.length; i++) { if (a[i] > maxval) { maxval = a[i]; } int histo [] = new int [maxval + 1]; for (int i = 0; i < a.length; i++) { histo[a[i]]++; } return histo; } public static int [] histogram (int [] a) // unspecified { int maxval = 0; for (int i = 0; i < a.length; i++) { if (a[i] > maxval) { maxval = a[i]; } int histo [] = new int [maxval + 1]; for (int i = 0; i < a.length; i++) { histo[a[i]]++; } return histo; } How many paths? Arrays are bounded in java: maximum size is First loop: … Second loop: path completely determined by first loop

Path-Complete Testing Insufficient One execution of a path doesn’t cover all behaviors Often bugs are missing paths Impossible Most programs have an “infinite” number of paths Branching Can test all paths Loops and recursion Test with zero, one and several iterations

Coverage Testing Statement Coverage: number of statements executed on at least one test number of statements in program Can we achieve 100% statement coverage?

Testing Recap Testing can find problems, but cannot prove your program works – Since exhaustive testing is impossible, select test cases with maximum likelihood of finding bugs – A successful test case is one that reveals a bug in your program! Typically at least 40% of cost of software project is testing, often >80% of cost for safety-critical software

Is it really hopeless? Since we can’t test all possible paths through a program, how can we increase our confidence that it works?

Analysis Make claims about all possible paths by examining the program code directly – Testing (dynamic analysis): checks exactly one program path – Static analysis: reasons about all possible program paths Use formal semantics of programming language to know what things mean Use formal specifications of procedures to know that they do

Hopelessness of Analysis It is impossible to correctly determine if any interesting property is true for an arbitrary program! The Halting Problem: it is impossible to write a program that determines if an arbitrary program halts.

Compromises Use imperfect automated tools: – Accept unsoundness and incompleteness – False positives: sometimes an analysis tool will report warnings for a program, when the program is actually okay (unsoundness) – False negatives: sometimes an analysis tool will report no warnings for a program, even when the program violates properties it checks (incompleteness) Java compiler warnings attempt to do this Use informal reasoning

Dealing with Hopelessness Since both testing and analysis are hopeless in general what can we do? Design for Testability Design for Analyzability

Programming Defensively

Assertions Statement ::= assert booleanExpression optStringExpression; booleanExpression ::= [any Java expression that evaluates to a boolean value] optStringExpression ::=  | : stringExpression stringExpression ::= [any Java expression that can be converted to a String value] Semantics: To evaluate an assert statement, evaluate the booleanExpression. If the booleanExpression evaluates to true, do nothing. If it is false, the assertion fails and an AssertionException thrown. If there is an optional stringExpression, it is evaluated (and converted to a String) and included in the AssertionException. Semantics: To evaluate an assert statement, evaluate the booleanExpression. If the booleanExpression evaluates to true, do nothing. If it is false, the assertion fails and an AssertionException thrown. If there is an optional stringExpression, it is evaluated (and converted to a String) and included in the AssertionException.

Enabling Assertions Without this, assert does nothing!

Examples public class TestClass { public static double divide(int a, int b) { assert b != 0; return (double) a / b; } public static void main(String[] args) { System.out.println (divide (3, 4)); System.out.println (divide (3, 0)); } 0.75 Exception in thread "main" java.lang.AssertionError at ps3.TestClass.divide(TestClass.java:6) at ps3.TestClass.main(TestClass.java:16)

Examples public class TestClass { public static double divide(int a, int b) { assert b != 0 : "Division by zero"; return (double) a / b; } public static void main(String[] args) { System.out.println (divide (3, 4)); System.out.println (divide (3, 0)); } 0.75 Exception in thread "main" java.lang.AssertionError: Division by zero at ps3.TestClass.divide(TestClass.java:6) at ps3.TestClass.main(TestClass.java:16)

Tricky Example public static double divide(int a, int b) { assert b != 0 : divide(a, b); return (double) a / b; } public static void main(String[] args) { System.out.println (divide (3, 4)); System.out.println (divide (3, 0)); } 0.75 Exception in thread "main" java.lang.StackOverflowError at ps3.TestClass.divide(TestClass.java:6) …

Where should we use assert? public static int [] histogram (int [] a) { int maxval = 0; for (int i = 0; i < a.length; i++) { if (a[i] > maxval) { maxval = a[i]; } int histo [] = new int [maxval + 1]; for (int i = 0; i < a.length; i++) { histo[a[i]]++; } return histo; } public static int [] histogram (int [] a) { int maxval = 0; for (int i = 0; i < a.length; i++) { if (a[i] > maxval) { maxval = a[i]; } int histo [] = new int [maxval + 1]; for (int i = 0; i < a.length; i++) { histo[a[i]]++; } return histo; } 1.To give useful debugging information when a REQUIRES precondition is violated. 2.To check assumptions on which our code relies. Judicious use of asserts: saves debugging time provides useful documentation increases confidence in results Judicious use of asserts: saves debugging time provides useful documentation increases confidence in results

How many assertions? About 5% of the statements in a good Java program should be asserts! Gunnar Kudrjavets, Nachiappan Nagappan, Thomas Ball. Assessing the Relationship between Software Assertions and Code Quality: An Empirical Investigation assertions per 1000 lines of code

Exceptions

Violating Requires In C/C++: can lead to anything – Machine crash – Security compromise – Strange results In Java: often leads to runtime exception When an assert fails, it generates an Exception. Other failures also generate Exceptions.

Use Exceptions to Remove Preconditions public static int biggest (int [ ] a) // REQUIRES: a has at least one element // EFFECTS: Returns the value biggest // element of a. public static int biggest (int [ ] a) throws NoElementException // REQUIRES: true // EFFECTS: If a has at least one element, returns the // value biggest element of a. Otherwise, throws // NoElementException.

Using Biggest with Requires public static int biggest (int [ ] a) // REQUIRES: a has at least one element // EFFECTS: Returns the value biggest // element of a. public static void main(String[] args) { int [] x = new int [0]; System.out.println ("Biggest: " + biggest(x)); … Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at ps3.TestClass.biggest(TestClass.java:6) at ps3.TestClass.main(TestClass.java:37)

Implementation public static int biggest (int [] a) { int res = a[0]; for (int i = 1; i < a.length; i++) { if (a[i] > res) res = a[i]; } return res; } Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at ps3.TestClass.biggest(TestClass.java:6) at ps3.TestClass.main(TestClass.java:37) public static int biggest (int [] a) { assert a != null && a.length > 0; int res = a[0]; for (int i = 1; i < a.length; i++) { if (a[i] > res) res = a[i]; } return res; } Exception in thread "main" java.lang.AssertionError at ps3.TestClass.biggest(TestClass.java:9) at ps3.TestClass.main(TestClass.java:46)

Using Biggest with Exception public static int biggest (int [ ] a) throws NoElementException // REQUIRES: true // EFFECTS: If a has at least one element, returns the // value biggest element of a. Otherwise, throws // NoElementException. public static void main(String[] args) { int [] x = new int [0]; System.out.println ("Biggest: " + biggest(x)); … TestClass.java:line 41 Unhandled exception type NoElementException This is a compile-time error: you cannot even run this code.

Catching Exceptions public static int biggest (int [ ] a) throws NoElementException // EFFECTS: If a has at least one element, returns the // value biggest element of a. Otherwise, throws // NoElementException. try { System.out.println ("Biggest: " + biggest(x)); } catch (NoElementException e) { System.err.println ("No element exception: " + e); } Statement ::= CatchStatement CatchStatement ::= try Block Handler* OptFinally Handler ::= catch (ExceptionType Var) Block OptFinally ::= finally Block |  Block ::= { Statement* } Statement ::= CatchStatement CatchStatement ::= try Block Handler* OptFinally Handler ::= catch (ExceptionType Var) Block OptFinally ::= finally Block |  Block ::= { Statement* }

Throwing Exceptions What is NoElementException? public static int biggest (int [] a) throws NoElementException { if (a == null || a.length == 0) { throw new NoElementException(); } int res = a[0]; for (int i = 1; i < a.length; i++) { if (a[i] > res) res = a[i]; } return res; }

Exceptions are Objects java.lang.Object java.lang.Throwable java.lang.Exception ps2.NoElementException We will cover subtyping and inheritance soon. class NoElementException extends Exception { }

public Document(String fname, int window) REQUIRES fname is the pathname for a readable file EFFECTS Creates a new document from the file identified by fname using window size window. public Document(String fname, int window) throws FileNotFoundException EFFECTS If fname is a readable file, creates a new document from that file using window size window. Otherwise, throws FileNotFoundException.

Using Document LabeledGraph g = new LabeledGraph(); Document d; try { d = new Document(file, window); g.addNode(file); } catch (FileNotFoundException fnfe) { System.err.println("Error: cannot open file: " + file + " [" + fnfe + "]"); } catch (DuplicateNodeException e) { System.err.println("Error: duplicate file: " + file); }

Mantra Be Assertive! Use assertions judiciously Exception Exceptionally Use exceptions to deal with exceptional circumstances Handling exceptions is tricky: code can jump from anywhere inside to the catch handler!

Charge Next class: designing and using exceptions exceptionally Reading: finish Chapter 5 and Chapter 10 “Surprise” quiz possible on Tuesday Problem Set 3: Designing and Implementing Data Abstractions will be posted by tomorrow, due Sept 21