1 Defensive Programming CIS*2450 Advanced Programming Concepts.

Slides:



Advertisements
Similar presentations
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
Advertisements

Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
Recitation By yzhuang, sseshadr. Agenda Debugging practices – GDB – Valgrind – Strace Errors and Wrappers – System call return values and wrappers – Uninitialization.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Debugging Techniques1. 2 Introduction Bugs How to debug Using of debugger provided by the IDE Exception Handling Techniques.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
API Design CPSC 315 – Programming Studio Fall 2008 Follows Kernighan and Pike, The Practice of Programming and Joshua Bloch’s Library-Centric Software.
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.
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. 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.
20 February Detailed Design Implementation. Software Engineering Elaborated Steps Concept Requirements Architecture Design Implementation Unit test Integration.
Debugging Logic Errors CPS120 Introduction to Computer Science Lecture 6.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
PRAGMATIC PARANOIA Steven Hadfield & Anthony Rice.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
Java for enterprise networks Version 2.3 Feb 2008 JSP Validation and Exception handling Why validate? Client side validation.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Handling ErrorstMyn1 Handling Errors Up to this point we haven't worried much about errors or exceptions. First, let's distinguish between errors and exceptions.
Software Construction and Evolution - CSSE 375 Defensive Programming & Error Handling Shawn & Steve Above – As you see behind me on the shelf, there are.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
1 Debugging and Testing Overview Defensive Programming The goal is to prevent failures Debugging The goal is to find cause of failures and fix it Testing.
C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a ‘wrappered function’? –What is a clean interface? –How to earn your.
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.
Testing Michael Ernst CSE 140 University of Washington.
Testing CSE 140 University of Washington 1. Testing Programming to analyze data is powerful It’s useless if the results are not correct Correctness is.
1 Assertions. 2 assertions communicate assumptions about the state of the program, and stop processing if they turn out to be false very often comments.
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.
Exceptions Handling Exceptionally Sticky Problems.
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Exceptions and assertions CSE 331 University of Washington.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
Design - programming Cmpe 450 Fall Dynamic Analysis Software quality Design carefully from the start Simple and clean Fewer errors Finding errors.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Testing CSE 160 University of Washington 1. Testing Programming to analyze data is powerful It’s useless (or worse!) if the results are not correct Correctness.
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.
Defensive Programming CNS 3370 Copyright 2003, Fresh Sources, Inc.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Announcements Partial Credit Due Date for Assignment 2 now due on Sat, Feb 27 I always seem to be behind and get tons of daily. If you me and.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
Introduction to Exceptions in Java CS201, SW Development Methods.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 17 – Specifications, error checking & assert.
Chapter 6 CS 3370 – C++ Functions.
CSE 374 Programming Concepts & Tools
Logger, Assert and Invariants
Handling Exceptionally Sticky Problems
Defensive Programming
CSE 374 Programming Concepts & Tools
Testing and Debugging.
Testing UW CSE 160 Winter 2017.
CSE 143 Error Handling [Section 2.8] 3/30/98 CSE 143.
Conditions and Ifs BIS1523 – Lecture 8.
Testing UW CSE 160 Winter 2016.
CSC 143 Error Handling Kinds of errors: invalid input vs programming bugs How to handle: Bugs: use assert to trap during testing Bad data: should never.
Handling Exceptionally Sticky Problems
CMSC 202 Exceptions.
Defensive Programming
Design Contracts and Errors A Software Development Strategy
Presentation transcript:

1 Defensive Programming CIS*2450 Advanced Programming Concepts

2 Series on Testing 1.Defensive programming Detect problems as early as possible 2.Intro. to testing Classic testing methods for “finished” code 3.Debugging Fixing defects uncovered by testing

3 1.Defensive Programming It’s like “Defensive Driving” You expect “unexpected” problems to crop up –her turn is signal on, but car doesn’t turn –you brake, but he doesn’t slow down behind Some areas for “suspicious” programming: –input data, not as specified function arguments, file contents, human input –module behaviour, not as specified

4 Need Error Handling Strategy Defensive programming uncovers “errors” –Now, what are you going to do about them? if (error happened) { what code goes here? } Best to have thought-out strategy re errors Don’t leave up to individual coder’s judgment Don’t handle on ad hoc basis –Otherwise, code quality (re error checking & handling) will vary widely across system

5 See Guidelines on Asmt Website 1. If the spec calls for some particular treatment… 2. If you run into the problem while trying to complete the processing… 3. If you complete the function's processing without finding a problem… This is example of “error handling strategy” suitable for student assignments

6 Striking a Balance One extreme: –Check for every conceivable (and inconceivable) error condition –Downside: Costs time/money to write that code Error checking/handling code must be tested, too! Takes up memory with code never likely to run Other extreme: “nothing will go wrong!” Fragile system, late discovery of hard-to-locate bugs

7 Recognize Two Kinds of Errors 1.Problems with external data/conditions –User/operator should be informed; don’t crash! 2.Erroneous internal usage, rare conditions Module A calls module B with bad args Out of memory/disk space Unexpected error return/result from library function call –Testing/debug phase: Let programmers know before crashing –Production phase: Keep running, recover gracefully if possible

8 Recognize Two Severities 1.“Fatal” errors: –Meaningless to continue execution e.g., out of memory, nonsensical value of critical variable –Best to abort, but inform if possible Otherwise, how will anyone find the bug? 2.“Nonfatal” errors: –Recovery possible, may want to inform

9 After Detection, Who Handles? General principle: –Handle errors in context, in the same place where you detected them You're aware an error may occur, might as well write the code to handle it while you know what the problem is

10 Benefits of Local Error Handling Avoids letting invalid state propagate elsewhere through other modules Self-documenting: –Clear idea what the (usually complex) error handling code is supposed to be there for Keeps the complex code for particular error contained and localized instead of smeared throughout the system

11 When to Reflect Errors Upward Utility packages are exception! (marcutil) –Can detect errors, but may not know how to handle in way acceptable to application E.g., utility printing error message usually not appropriate App. may have special use of stdout/stderr streams, may be running in GUI Best: reflect error status up to caller –Caller applies “handle error in context” principle to suit nature of application

12 Tools for Reporting Errors Unconditional, allow recovery/continuation fprintf(stderr, … ) –nonbuffered stream, crash won’t prevent output syslog: uses OS event logging facility –#include ; “man openlog” for help Conditional: print & abort or continue quietly assert(expression) –#include ; “man assert” for help

13 Using Assertions expression==0 (meaning “false”) → assertion fails, prints message on stdout and calls abort() Good way to handle improbable conditions likely arising from bugs where you just want to abort –verifying preconditions in functions (misuse by caller) –verifying malloc not NULL (allocation gone wild) –DON’T use for testing input data –see Linux Programming, pp

14 Turning Assertions On/Off Turned on by default –helpful printout: source file, line no., function name –aborts program Turn off at compile time –insert line: #define NDEBUG –makefile: gcc … -DNDEBUG Since could be either on/off, assertion must not have side effects! i.e., code that has to be executed

15 When will this code fail? Utility double avg ( double a[], int n) { int i; double sum = 0.0; for ( i=0; i < n; i++ ) sum = sum + a[i]; return ( sum/(double)n ); } #include double avg ( double[], int ); int main ( int argc, char *argv[] ) { int count = argc - 1; double array[100]; int i; for ( i=1; i <= count; i++ ) array[i-1] = atof(argv[i]); printf("Avg=%f\n",avg(array,count); }

16 When will this code fail? > testzero Avg= > testzero Avg=NaN

17 Using Assertions In testzero.c, avg function: #include assert( n>0 ); Running with no arguments: testzero testzero.c:15: avg: Assertion ‘n>0’ failed. Is this a good use of assert? –Yes: verifies precondition of avg –Catches bug in main(): main should check for 0 args –Production phase: can turn off assertion

18 Bad Use of Assertion Can main() check for 0 args with assert()? –No: bad use! 0 args is due to external input Contrast violation of internal utility’s precondition –“Assert” not substitute for input validation code –Best: print message telling user to type at least one number

19 What to Check For Check for cases which “can't occur” just in case! Check for extreme values - negative values, huge values, etc. if ( grade 100 ) /* impossible grades! */ letter = '?'; else if ( grade >= 80 ) letter = 'A'; else... Check for NULL pointers, out of range subscripts, default switch case, divide by zero

20 What to Check For Check pre- and post-conditions –before and after a critical piece of code, check to see if the necessary pre- and post-conditions (value of variables, etc.) hold true Famous divide by zero error: On the USS Yorktown (guided-missile cruiser), a crew member entered a zero, which resulted in a divide by zero, the error cascaded and shut down the propulsion system and the ship drifted for a couple of hours.

21 What to Check For Check error returns –Don’t take for granted that status is OK –Always look at the values returned from library functions and system calls (see man pages) –Remember to check for output errors and failures as well as input failures - fprintf, fwrite Bad status: print text message, not error no. –“man” strerror function, errno global variable

22 On to Testing! Defensive programming = some degree of self-testing code –Tests itself at development time –Continues testing in production Still need to methodically apply tests to modules, system as whole –Practices very well developed in SW engr. –Can only introduce in 2450, more in 3430/3200