How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation www.telerik.com.

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.
Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
COMP 121 Week 5: Exceptions and Exception Handling.
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.
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
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.
Software Construction 1 ( ) First Semester Dr. Samer Odeh Hanna (PhD) Office: IT 327.
Debugging Techniques1. 2 Introduction Bugs How to debug Using of debugger provided by the IDE Exception Handling Techniques.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
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 in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
PRAGMATIC PARANOIA Steven Hadfield & Anthony Rice.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
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.
Software Construction and Evolution - CSSE 375 Defensive Programming & Error Handling Shawn & Steve Above – As you see behind me on the shelf, there are.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Slides Credit Umair Javed LUMS Web Application Development.
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.
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.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
Introduction to Exception Handling and Defensive Programming.
Defensive Programming, Assertions and Exceptions Designing Fault-Resistant Code SoftUni Team Technical Trainers Software University
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
Programming with Assertions © Allan C. Milne v
Defensive Programming, Assertions and Exceptions Designing Error Steady Code SoftUni Team Technical Trainers Software University
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
Chapter 8-Exception Handling/ Robust Programming.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
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.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
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.
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.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 6 CS 3370 – C++ Functions.
Defensive Programming
Testing and Debugging.
Coding Defensively Coding Defensively
Software Construction
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.
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exception Handling.
Software Construction
Presentation transcript:

How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation

Using Assertions and Exceptions Correctly

 Similar to defensive driving – you are never sure what other drivers will do  Expect incorrect input and handle it correctly  Think not only about the usual execution flow, but consider also unusual situations 3

 “Garbage in, garbage out.” – NO!  Garbage in - nothing out, error message out or no garbage allowed in  Check the values of all data from external sources (a user, a file, internet, etc.) 4

 Check method preconditions – parameters, object state  Check method postconditions – what is guaranteed to the caller 5 string Substring(string str, int startIndex, int length) { REQUIRE(str != NULL); REQUIRE(str != NULL); REQUIRE(startIndex >= str.Length); REQUIRE(startIndex >= str.Length); REQUIRE(startIndex + count > str.Lenght); REQUIRE(startIndex + count > str.Lenght); string result = … string result = … ENSURE(result.Length == length); ENSURE(result.Length == length);} preconditions main logic postconditions.

 A statement placed in code that must always be true at that place  Assertions are used during development, they are removed during production compilation  Assertions check for bugs in code 6 void GetAvarageStudentGrade() { Debug.Assert(studentGrades.Count > 0, “student grades are not initialized”); Debug.Assert(studentGrades.Count > 0, “student grades are not initialized”); return studentGrades.Avarage(); return studentGrades.Avarage();}

 Use assertions for conditions that should never occur  Use assertions to document assumptions made in code  document preconditions and postconditions 7 private Student GetRegisteredStudent(int id) { Debug.Assert(id > 0); Debug.Assert(id > 0); Student student = registeredStudents[id]; Student student = registeredStudents[id]; Debug.Assert(student.IsRegistered); Debug.Assert(student.IsRegistered);}

 Failed assertion indicates a fatal error in the program (usually unrecoverable)  Avoid putting executable code in assertions  Won’t be compiled in production. Better:  Assertions should fail loud 8 assert PerformAction() : “Could not perform action” bool actionedPerformed = PerformAction(); assert actionedPerformed : “Could not perform action”

 How do you handle errors that you expect to occur?  Depends on the situation. Examples:  Return a neutral value  Return the same answer as the previous time  Log a warning message to a file  Return an error code  Display an error message  Shutdown  Throw an exception 9

 How will you handle error while calculating single pixel color in a computer game?  How will you handle error while calculating single pixel color in a X-Ray software?  Correctness - never returning an inaccurate result.  Robustness - always trying to do something that will allow the software to keep running. 10

 Choose your error handling strategy and follow it consistently  Strongly consider using exceptions 11

 Exceptions are a specific means by which code can pass along errors or exceptional events to the code that called it  Methods throw exceptions: 12 public void ReadInput(string input) { if(input == null) if(input == null) { throw new ArgumentNullException(“input”); } throw new ArgumentNullException(“input”); } …}

 Use try-catch statement to handle exceptions:  You can use multiple catch blocks to specify handlers for different exceptions.  Not handled exceptions propagate to the caller 13 void playNextTurn() { try { try { … readInput(input); … readInput(input); … } catch(ArgumentNullException e) { … } catch(ArgumentNullException e) { console.printLine(“Hello from catch!”); console.printLine(“Hello from catch!”); }} Exception thrown here Code here won’t be executed

 Use finally block to execute code even if exception occurs (not supported in C++):  Perfect place to perform cleanup for any resources allocated in the try block. 14 void playNextTurn() { try { try { … readInput(input); … readInput(input); … } finally { … } finally { console.printLine(“Hello from finally!”); console.printLine(“Hello from finally!”); }} Exception thrown here Code here is always executed

 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  Should I throw an exception when checking for user name and password?  Don’t use exceptions as control flow mechanisms 15

 Throw exceptions at the right level of abstraction 16 class Employee { … public TaxId getTaxId() throws EOFException { public TaxId getTaxId() throws EOFException { … }} class Employee { … public TaxId getTaxId() throws EmployeeDataNotAvailable { public TaxId getTaxId() throws EmployeeDataNotAvailable { … }}

 Use descriptive error messages  Incorrect example:  Example:  Avoid empty catch blocks 17 throw new Exception("Error!"); throw new ArgumentException("The speed should be a number " + "between " + MIN_SPEED + " and " + MAX_SPEED + "."); "between " + MIN_SPEED + " and " + MAX_SPEED + "."); try { … // lots of code // lots of code … } catch(Exception ex){ }

 Always include the exception cause when throwing a new exception 18 try{ WithdrawMoney(account, amount); WithdrawMoney(account, amount);} catch (DatabaseException dbex) { throw new WithdrawException(String.Format( throw new WithdrawException(String.Format( "Can not withdraw the amount {0} from acoount {1}", "Can not withdraw the amount {0} from acoount {1}", amount, account), dbex); amount, account), dbex);} We include in the exceptions chain the original source of the problem.

 Catch only exceptions that you are capable to process correctly  Do not catch all exceptions  Incorrect example:  What about OutOfMemoryException ? 19 try{ ReadSomeFile(); ReadSomeFile();}catch{ Console.WriteLine("File not found!"); Console.WriteLine("File not found!");}

 Have an exception handling strategy for unexpected/unhandled exception:  Consider logging (log4net, log4j, log4cplus).  Display to the end users only messages that they could understand 20 or

 Exceptions are announcements about error condition or unusual event  Inform the caller about error or exceptional event  Can be caught and application can continue working  Assertions are fatal errors  Assertions always indicate bugs in the code  Can not be caught and processed  Application can’t continue in case of failed assertion  When in doubt – throw exception 21

22 public string Substring(string str, int startIndex, int length) { if (str == null) if (str == null) { throw new NullReferenceException("Str is null."); throw new NullReferenceException("Str is null."); } if (startIndex >= str.Length) if (startIndex >= str.Length) { throw new ArgumentException( throw new ArgumentException( "Invalid startIndex:" + startIndex); "Invalid startIndex:" + startIndex); } if (startIndex + count > str.Length) if (startIndex + count > str.Length) { throw new ArgumentException("Invalid length:" + length); throw new ArgumentException("Invalid length:" + length); } … Debug.Assert(result.Length == length); Debug.Assert(result.Length == length);} Check the input and preconditions. Perform the method main logic. Check the postconditions.

 Barricade your program to contain the damage caused by errors  Behind the barricade is “safe” area - data is valid  Validate data crossing the boundary  Consider same approach for class design  Public methods validate the data  Private methods assume the data is safe  Consider using exceptions for public methods and assertions for private 23

 Don’t automatically apply production constraints to the development version  Be willing to trade speed and resource usage during development  Introduce debugging aids early  Make errors obvious during development  Asserts should abort the program  Unhandled exceptions should not be hidden  Plan for removing debugging aids 24

 Too much defensive programming is not good – strive for balance  How much defensive programming to leave in production code  Remove code that results in hard crashes  Leave in code that checks for important errors  Log errors for your technical support personnel  See that the error messages you leave in are friendly 25

Questions?