Software Construction and Evolution - CSSE 375 Defensive Programming & Error Handling Shawn & Steve Above – As you see behind me on the shelf, there are.

Slides:



Advertisements
Similar presentations
Chapter 5 Errors Bjarne Stroustrup
Advertisements

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.
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
GoogleTest Primer. Outline Basic Concepts Assertions Basic Assertions Binary Comparison String Comparison Floating-Point Comparison Simple Tests Test.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 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.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
1 CSC241: Object Oriented Programming Lecture No 28.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 7: Errors 1 Based on slides created by Bjarne Stroustrup.
Software Construction 1 ( ) First Semester Dr. Samer Odeh Hanna (PhD) Office: IT 327.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
1 Defensive Programming CIS*2450 Advanced Programming Concepts.
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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
JUnit, Revisited 17-Apr-17.
Software Testing. “Software and Cathedrals are much the same: First we build them, then we pray!!!” -Sam Redwine, Jr.
28/08/2015SJF L31 F21SF Software Engineering Foundations ASSUMPTIONS AND TESTING Monica Farrow EM G30 Material available on Vision.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
1 Exceptions and error handling. 2 Java exception mechanism when an error or exceptional condition occurs, you throw an exception which is caught by an.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
1 Defensive Programming and Debugging (Chapters 8 and 23 of Code Complete) Tori Bowman CSSE 375, Rose-Hulman September 21, 2007.
Chapter 12: Exception Handling
Routines and Defensive Programming Chapter 7-8 McConnell.
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.
ICAPRG301A Week 4Buggy Programming ICAPRG301A Apply introductory programming techniques Program Bugs US Navy Admiral Grace Hopper is often credited with.
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.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Exceptions Handling Exceptionally Sticky Problems.
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
1 Software Construction and Evolution - CSSE 375 Exception Handling - Principles Steve Chenoweth, RHIT Above – Exception handling on the ENIAC. From
Introduction to Exception Handling and Defensive Programming.
Exceptions and assertions CSE 331 University of Washington.
Defensive Programming, Assertions and Exceptions Designing Fault-Resistant Code SoftUni Team Technical Trainers Software University
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Making Good Code AKA: So, You Wrote Some Code. Now What? Ray Haggerty July 23, 2015.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
Defensive Programming, Assertions and Exceptions Designing Error Steady Code SoftUni Team Technical Trainers Software University
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.
Exception Handling Outline 23.1 Introduction
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
CSC 108H: Introduction to Computer Programming
Chapter 6 CS 3370 – C++ Functions.
Logger, Assert and Invariants
Handling Exceptionally Sticky Problems
Defensive Programming
Testing and Debugging.
Chapter 14: Exception Handling
Software Construction
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Handling Exceptionally Sticky Problems
Exceptions 5-Jul-19.
Software Construction
Defensive Programming
Presentation transcript:

Software Construction and Evolution - CSSE 375 Defensive Programming & Error Handling Shawn & Steve Above – As you see behind me on the shelf, there are two worlds. I live in the one where you can be a pacifist, and it is pragmatic.

2 Defensiveness  What does it mean to be defensive?  When are we defensive?  Good defense?  Not so good defense? Right - In the chess game shown, black has just moved the pawn from e5-e6. This suggests that moving the knight on d7 also will provide mobility to the bishop on c8, as shown. The ability to handle unforeseen circumstances defensively is a part of playing black in chess. The setup shown is a part of the “Cambridge Springs Defence.”

3 What is Defensive Programming?  Analogous to “Defensive Driving” l You expect “unexpected” problems to crop up  Protect against “suspicious” programming l Input data, not as specified l Function arguments, file contents, human input l Module behavior, not as specified Q1 Don’t let the dog drive!

4 Where do some Bad Smells come from?  “Garbage in, garbage out” (inappropriate for production code)  Check the values of all data from external sources  Check the values of all routine input parameters  Need to decide how to handle bad inputs Q2

5 Unsafe Programming Constructs  Pointers  Dynamic memory allocation  Floating-point numbers  Parallelism  Recursion  Interrupts All are valuable in specific circumstances, but should be used with discretion Q3

6 Need Error Handling Strategy  Defensive programming uncovers “errors” if (error happened) { what code goes here? }  Best to have a planned strategy regarding errors

7 Uniformity in Error Handling Strategy  Don’t leave up to individual coder’s judgment  Don’t handle on ad hoc basis  Otherwise, code quality (via error checking & handling) will vary widely across system General principle: Handle errors in context, in the same place where you detected them Q4

8 Handling Expected Errors  Return a neutral value l Might continue operating but return a neutral value known to be harmless –Empty string, 0, etc.  Substitute next piece of valid data l Typically when processing a stream, e.g. reading from a file or sampling data  Return the same answer as the previous time l E.g. temperature reading software sampling  Substitute the closest legal value Q5-1

9 Handling Expected Errors (continued)  Log a warning message to a file  Return an error code l Set a status variable, throw exception  Call a centralized error processing routine l Hard to reuse though in other programs  Display an error message  Depends on context… even Shut down Q5-2

10 Exercise: Catching Expected Errors  Your company has a new website that offers a great new Computer Advice and Review center. You know that your audience would be likely to try and get in to get at your goodies without a subscription. What “Error Handling” strategy would you consider? Q6

11 Need to Strike a Balance  One extreme: l Check for every conceivable (and inconceivable) error condition  Other extreme: “nothing will go wrong!” –Fragile system, late discovery of hard-to-locate bugs Q7

12 Recognize Two Kinds of Errors 1. Problems with external data/conditions l User/operator should be informed; don’t crash! 2. Erroneous internal usage …rare conditions –Module A calls module B with bad arguments –Out of memory/disk space –Unexpected error return/result from library function call

13 Recognize Three Severities 1. “Fatal” errors 2. “Nonfatal” errors now, but potentially “fatal” later 3. “Nonfatal” errors Q8

14 When to Reflect Errors Upward  Best: reflect error status up to caller l Caller applies “handle error in context” principle to suit nature of application  Utility packages are the exception! l Can detect errors, but may not know how to handle in way acceptable to application

15 Defensive Programming Techniques  Assertions  Exception handling  Code Insertion Note: These techniques can also be used elsewhere besides defensive programming

16 Assertions  Assertions are code used to check if everything is operating as expected l Assertion takes an input that’s supposed to be true, and a message to display if it isn’t assert (denominator != 0) : “Denominator not zero”  Use to document assumptions made in code and flush out error conditions  Assertions are intended to always be silent

17 Exceptions  Use exceptions to notify other parts of the program about errors that should not be ignored  Throw an exception only for conditions that are “truly exceptional”  Don’t use an exception to pass the buck l If can handle it locally, do it

18 Exceptions (continued)  Avoid throwing exceptions in constructors and destructors  Throw exceptions at the right level of abstraction class Employee { … public TaxId GetTaxId() throws EOFException { … }

19 What are Alternatives to Exceptions?  Handling the error locally  Propagating error with appropriate error code  Logging debug information to a file  Extremes: Shutdown or Ignoring it  “Sometimes the best response to a serious run- time error is to release all acquired resources and abort. Let the user rerun the program with proper input.” Bjarne Stroustrup

20 Code Insertion: Debugging Aids  Common Assumption: Developer version can be slow, but production version must be fast (stingy with resources)  Microsoft Word l Code in the idle loop that checks the integrity of the Document object l Helps detect data corruption more quickly and easier error diagnosis / recovery

21 Offensive Programming  Exceptional cases should be handled in a way that makes them obvious during development and recoverable when production code is running  Make sure asserts abort the program l Don’t allow programmers to get in the habit of hitting enter to bypass known problems, make it painful so it will get fixed  Completely fill any memory allocated l So you can detect memory allocation errors

22 Offensive Programming (continued)  Completely fill any files or streams allocated l To flush out file format errors  Ensure code in case statement’s default clause fails hard or is impossible to overlook  Fill an object with junk before it is deleted  error log files to yourself

23 How much defensive code to Leave?  Leave in code that l Checks for important errors l Helps the program crash gracefully  Remove code that l Checks for trivial errors l Hard crashes as a “signal” to testers –Replace with graceful crash :-)  Log errors for technical support

24 Social Defensive Programming Idea: Documentation might be ignored, but invoking the function name or variable can’t l ReferenceType MyClass::GetPointerDoNotDelete() l SafeHandle.DangerousGetHandle() l m_dontUseMe