Software Construction 1 (0721385) First Semester 2014-2015 Dr. Samer Odeh Hanna (PhD) Office: IT 327.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
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.
1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
Written by: Dr. JJ Shepherd
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
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.
Understand Error Handling Software Development Fundamentals LESSON 1.4.
Chapter 8 Designing Classes. Assignment Chapter 9 Review Exercises (Written)  R8.1 – 8.3, 8.5 – 8.7, 8. 10, 8.11, 8.13, 8.15, 8.19, 8.20 Due Friday,
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Software Testing and Quality Assurance
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
Computer Science 340 Software Design & Testing Design By Contract.
Exceptions COMPSCI 105 S Principles of Computer Science.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Code Complete Steve McConnell.
PRAGMATIC PARANOIA Steven Hadfield & Anthony Rice.
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.
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
Software Construction and Evolution - CSSE 375 Defensive Programming & Error Handling Shawn & Steve Above – As you see behind me on the shelf, there are.
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.
Defensive Programming 1 Nikolaus Embgen. Topics 1.Motivation 2.The concept 3.What can we do? 4.How to use this? 5.What else can we do? 6.The conclusion.
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 the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
Exceptions Handling Exceptionally Sticky Problems.
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
Introduction to Exception Handling and Defensive Programming.
Black Box Testing Techniques Chapter 7. Black Box Testing Techniques Prepared by: Kris C. Calpotura, CoE, MSME, MIT  Introduction Introduction  Equivalence.
Defensive Programming, Assertions and Exceptions Designing Fault-Resistant Code SoftUni Team Technical Trainers Software University
Today’s Agenda  Reminder: HW #1 Due next class  Quick Review  Input Space Partitioning Software Testing and Maintenance 1.
Programming with Assertions © Allan C. Milne v
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Defensive Programming, Assertions and Exceptions Designing Error Steady Code SoftUni Team Technical Trainers Software University
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exception Handling Outline 23.1 Introduction
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
CIS 200 Test 01 Review. Built-In Types Properties  Exposed “Variables” or accessible values of an object  Can have access controlled via scope modifiers.
Chapter 8-Exception Handling/ Robust Programming.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
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.
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.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
Chapter 6 CS 3370 – C++ Functions.
Logger, Assert and Invariants
Defensive Programming
Testing and Debugging.
Why exception handling in C++?
Software Construction
Computer Science 340 Software Design & Testing
CMSC 202 Exceptions.
Software Construction
Defensive Programming
Design Contracts and Errors A Software Development Strategy
Presentation transcript:

Software Construction 1 ( ) First Semester Dr. Samer Odeh Hanna (PhD) Office: IT 327

Software Construction 2 Chapter 3: Defensive Programming

Software Construction 3 Introduction  The idea of defensive programming is based on defensive driving  In defensive programming, the main idea is that if a routine is passed bad data, it won't be hurt, even if the bad data is another routine's fault.

Software Construction Protecting Your Program from Invalid Inputs A good program never put out garbage, regardless of what it takes in. A good program uses:  "Garbage in, nothing out"  "Garbage in, error message out"  "No garbage allowed in"

Software Construction 5 There are three general ways to handle garbage in:  Check the values of all data from external sources  Attempt buffer overflows  Inject SQL commands  Inject HTML or XML code and so on  Check the values for all routine input parameters  Decide how to handle bad inputs

Software Construction Assertions  An assertion is code that is used during development that allows a program to check itself as it runs. When an assertion is true, that means everything is operating as expected, when it is false, that means it has detected an unexpected error in the code. assert denominator != 0 : "denominator is unexpectedly equal to 0.";

Software Construction 7 Guidelines for Using Assertions  Use error-handling code for conditions you expect to occur; use assertions for conditions that should never occur  Avoid putting executable code into assertions Visual Basis example of a dangerous use of an assertion Debug.Assert (PerformAction( ) ) ' Could no perform action Visual Basis example of a safe use of an assertion actionPerformed = PerformAction( ) Debug.Assert (actionPerformed )

Software Construction 8 Cont.  Use assertions to document and verify preconditions and Postconditions Visual Basic example of using assertions to document preconditions and Postconditions Private Function Velocity ( ByVal latitude As Single, ByVal longtitude As Single, ByVal elevation As Single ) As Single ' Preconditions Debug.Assert ( -90 <= latitude And latitude <=90) Debug.Assert ( 0 <= longitude And longitude <360) Debug.Assert ( -500 <= elevation And elevation <= 75000) ' PostConditions Debug.Assert ( 0 <= returnVelocity and returnVelocity <=600 ) ' return value Velocity = returnVelocity End Function

Software Construction 9  For highly robust code, assert and then handle the error anyway Visual Basic example of using assertions to document preconditions and Postconditions Private Function Velocity ( ByVal latitude As Single, ByVal longitude As Single, ByVal elevation As Single ) As Single Assertion code ' Preconditions Debug.Assert ( -90 <= latitude And latitude <=90) Debug.Assert ( 0 <= longitude And longitude <360) Debug.Assert ( -500 <= elevation And elevation <= 75000) ….. ' Sanitize input data. Values should be within the ranges asserted above ' but if a value is not within its valid range, it will be changed to the ' closet legal value If ( latitude < -90 ) Then Code that handles bad input data at run-time latitude = -90 ElseIf ( latitude > 90 ) Then latitude = 90 End If IF ( longitude < 0 ) Then Longitude = 0 ElseIF ( longitude > 360 ) Then … End Function

Software Construction Error-Handling Techniques 1. Return a neutral value 2. Substitute the next piece of valid data 3. Return the same answer as previous time 4. Substitute the closet legal value 5. Log a warning message to a file 6. Return an error code 7. Call an error-processing routine/object 8. Display an error message wherever the error is encountered 9. Handle the error in whatever way works best locally 10. Shut down

Software Construction 11 Differences between assertion and error handling techniques AssertionError Handling Technique An assertion is code that is used during development Error handling techniques is code that is used during development and after delivery assertions for conditions that should never occur error-handling code is used for conditions you expect to occur the corrective action is to change the program's source code, recompile, and release a new version of a software. the corrective action is merely to handle an error gracefully

Software Construction 12 Robustness vs. Correctness  Correctness means never returning an inaccurate result; returning no result is better than returning an inaccurate result.  Robustness means always trying to do something that will allow the software to keep operating, even if that leads to results that are inaccurate sometimes.  Some applications tend to favor correctness to robustness and others favor robustness to correctness.

Software Construction Exceptions  Exceptions are a specific means by which code can pass along errors or exceptional events to the code that called it. If code in one routine encounters an unexpected condition that it does not know how to handle, it throws an exception, essentially throwing up its hands and yelling, "I do not know what to do about this – I sure hope somebody else knows how to handle it!"  Visit for exampleshttp://

Software Construction 14 Example using System; class Program { static void Main() { try { int value = 1 / int.Parse("0"); Console.WriteLine(value); } catch (Exception ex) { Console.WriteLine(ex.Message); }

Software Construction 15 Custom Exception Example using System; class TestException : Exception { public override string Message { get { return "This exception means something bad happened"; } } class Program { static void Main() { try { throw new TestException(); } catch (TestException ex) { Console.WriteLine(ex.Message); }

Software Construction 16 Exceptions (Cont.) Suggestions for realizing the benefits of exceptions and avoiding the difficulties often associated with them.  Use exceptions to notify other parts of the program about errors that should not be ignored  If an error condition can be handled locally, handle it locally  Avoid throwing exceptions in constructors and destructors  Throw exceptions at the right level of abstraction  Include in the exception message all information that led to the exception

Software Construction 17 Cont.  Avoid empty catch blocks  Standardize your project's use of exceptions  Consider alternatives to exceptions

Software Construction Barricade  Barricade your Program to Contain the Damage Caused by Errors  Barricades are a damage-containment strategy  One way to barricade for defensive programming purpose is to design certain interfaces as boundaries to "safe" areas

Software Construction 19 Relationship between Barricades and Assertions  Routines that are outside the barricade should use error handling  Routines inside the barricade should use assertions

Software Construction 20 Questions?