Chapter 5 Errors Bjarne Stroustrup www.stroustrup.com/Programming.

Slides:



Advertisements
Similar presentations
Basics of Recursion Programming with Recursion
Advertisements

Chapter 17 vector and Free Store Bjarne Stroustrup
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Chapter 26 Testing Bjarne Stroustrup
Chapter 14 Graph class design Bjarne Stroustrup
Chapter 24 Numerics Bjarne Stroustrup
Chapter 4 Computation Bjarne Stroustrup
Chapter 6 Writing a Program
Error-handling using exceptions
Topics Introduction Types of Errors Exceptions Exception Handling
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
Why care about debugging? How many of you have written a program that worked perfectly the first time? No one (including me!) writes a program that works.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
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.
Errors Lecture 6 Hartmut Kaiser
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,
Section 2.4: Errors. Common errors ● Mismatched parentheses ● Omitting space after operator or between numbers ● Putting operator between operands.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 4: Enhancing Your Program.
CS211 Data Structures Sami Rollins Fall 2004.
CS 101 Problem Solving and Structured Programming in C Sami Rollins Spring 2003.
Testing a program Remove syntax and link errors: Look at compiler comments where errors occurred and check program around these lines Run time errors:
Advanced Java Course Exception Handling. Throwables Class Throwable has two subclasses: –Error So bad that you never even think about trying to catch.
Introduction To C++ Programming 1.0 Basic C++ Program Structure 2.0 Program Control 3.0 Array And Structures 4.0 Function 5.0 Pointer 6.0 Secure Programming.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering.
Variables in Java Part 2. ICS-3M1 - Mr. Martens - Variables Part 2 Recall the “int” Data Types When you divide one integer by another – you always get.
Lecture 4 Errors Bjarne Stroustrup
Chapter 12: Exception Handling
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
Jun 16, 2014IAT 2651 Debugging. Dialectical Materialism  Dialectical materialism is a strand of Marxism, synthesizing Hegel's dialectics, which proposes.
ICAPRG301A Week 4Buggy Programming ICAPRG301A Apply introductory programming techniques Program Bugs US Navy Admiral Grace Hopper is often credited with.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 5 Errors Hartmut Kaiser
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.
Testing E001 Access to Computing: Programming. 2 Introduction This presentation is designed to show you the importance of testing, and how it is used.
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?
Chapter 6 Writing a Program John Keyser’s Modification of Slides by Bjarne Stroustrup
Exceptions Handling Exceptionally Sticky Problems.
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.
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.
Testing. 2 Overview Testing and debugging are important activities in software development. Techniques and tools are introduced. Material borrowed here.
Introduction to Software Testing. Types of Software Testing Unit Testing Strategies – Equivalence Class Testing – Boundary Value Testing – Output Testing.
Errors “Computer says no..”. Types of Errors Many different types of errors new ones are being invented every day by industrious programming students..
1 Original Source : and Problem and Problem Solving.ppt.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 6 Writing a Program Hartmut Kaiser
1 Debugging and Syntax Errors in C++. 2 Debugging – a process of finding and fixing bugs (errors or mistakes) in a computer program.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Lesson - 2. Introduction When we make a program we must follow some steps, called Programming Development Life Cycle (PDLC). Programming steps are five:
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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.
AVCE ICT – Unit 7 - Programming Session 12 - Debugging.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Chapter 6 Writing a Program Bjarne Stroustrup
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.
Handling Exceptionally Sticky Problems
Defensive Programming
CSE 374 Programming Concepts & Tools
Testing and Debugging.
Errors Lecture 6 Hartmut Kaiser
Testing UW CSE 160 Spring 2018.
Bjarne Stroustrup Chapter 5 Errors Bjarne Stroustrup
Exceptions 19-Feb-19.
Exceptions 7-Apr-19.
An Introduction to Debugging
Handling Exceptionally Sticky Problems
Presentation transcript:

Chapter 5 Errors Bjarne Stroustrup

Cambridge Stroustrup/Programming2

CERN 3

Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications, incomplete programs, and our own errors. Here, well concentrate on a key area: how to deal with unexpected function arguments. Well also discuss techniques for finding errors in programs: debugging and testing. When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications, incomplete programs, and our own errors. Here, well concentrate on a key area: how to deal with unexpected function arguments. Well also discuss techniques for finding errors in programs: debugging and testing. 4Stroustrup/Programming

Overview Kinds of errors Kinds of errors Argument checking Argument checking Error reporting Error reporting Error detection Error detection Exceptions Exceptions Debugging Debugging Testing Testing 5Stroustrup/Programming

Errors … I realized that from now on a large part of my life would be spent finding and correcting my own mistakes. … I realized that from now on a large part of my life would be spent finding and correcting my own mistakes. Maurice Wilkes, 1949 Maurice Wilkes, 1949 When we write programs, errors are natural and unavoidable; the question is, how do we deal with them? When we write programs, errors are natural and unavoidable; the question is, how do we deal with them? Organize software to minimize errors. Organize software to minimize errors. Eliminate most of the errors we made anyway. Eliminate most of the errors we made anyway. Debugging Debugging Testing Testing Make sure the remaining errors are not serious. Make sure the remaining errors are not serious. My guess is that avoiding, finding, and correcting errors is 95% or more of the effort for serious software development. My guess is that avoiding, finding, and correcting errors is 95% or more of the effort for serious software development. You can do much better for small programs. You can do much better for small programs. or worse, if youre sloppy or worse, if youre sloppy 6Stroustrup/Programming

Your Program 1. Should produce the desired results for all legal inputs 2. Should give reasonable error messages for illegal inputs 3. Need not worry about misbehaving hardware 4. Need not worry about misbehaving system software 5. Is allowed to terminate after finding an error 3, 4, and 5 are true for beginners code; often, we have to worry about those in real software. 7Stroustrup/Programming

Sources of errors Poor specification Poor specification Whats this supposed to do? Whats this supposed to do? Incomplete programs Incomplete programs but Ill not get around to doing that until tomorrow but Ill not get around to doing that until tomorrow Unexpected arguments Unexpected arguments but sqrt() isnt supposed to be called with -1 as its argument but sqrt() isnt supposed to be called with -1 as its argument Unexpected input Unexpected input but the user was supposed to input an integer but the user was supposed to input an integer Code that simply doesnt do what it was supposed to do Code that simply doesnt do what it was supposed to do so fix it! so fix it! 8Stroustrup/Programming

Kinds of Errors Compile-time errors Compile-time errors Syntax errors Syntax errors Type errors Type errors Link-time errors Link-time errors Run-time errors Run-time errors Detected by computer (crash) Detected by computer (crash) Detected by library (exceptions) Detected by library (exceptions) Detected by user code Detected by user code Logic errors Logic errors Detected by programmer (code runs, but produces incorrect output) Detected by programmer (code runs, but produces incorrect output) 9Stroustrup/Programming

Check your inputs Before trying to use an input value, check that it meets your expectations/requirements Before trying to use an input value, check that it meets your expectations/requirements Function arguments Function arguments Data from input ( istream ) Data from input ( istream ) 10Stroustrup/Programming

Bad function arguments The compiler helps: The compiler helps: Number and types of arguments must match Number and types of arguments must match int area(int length, int width) { return length*width; } int x1 = area(7); // error: wrong number of arguments int x2 = area("seven", 2);// error: 1 st argument has a wrong type int x3 = area(7, 10);// ok int x5 = area(7.5, 10);// ok, but dangerous: 7.5 truncated to 7; // most compilers will warn you int x = area(10, -7); // this is a difficult case: // the types are correct, // the types are correct, // but the values make no sense 11Stroustrup/Programming

Bad Function Arguments So, how about int x = area(10, -7); So, how about int x = area(10, -7); Alternatives Alternatives Just dont do that Just dont do that Rarely a satisfactory answer Rarely a satisfactory answer The caller should check The caller should check Hard to do systematically Hard to do systematically The function should check The function should check Return an error value (not general, problematic) Return an error value (not general, problematic) Set an error status indicator (not general, problematic – dont do this) Set an error status indicator (not general, problematic – dont do this) Throw an exception Throw an exception Note: sometimes we cant change a function that handles errors in a way we do not like Note: sometimes we cant change a function that handles errors in a way we do not like Someone else wrote it and we cant or dont want to change their code Someone else wrote it and we cant or dont want to change their code 12Stroustrup/Programming

Bad function arguments Why worry? Why worry? You want your programs to be correct You want your programs to be correct Typically the writer of a function has no control over how it is called Typically the writer of a function has no control over how it is called Writing do it this way in the manual (or in comments) is no solution – many people dont read manuals Writing do it this way in the manual (or in comments) is no solution – many people dont read manuals The beginning of a function is often a good place to check The beginning of a function is often a good place to check Before the computation gets complicated Before the computation gets complicated When to worry? When to worry? If it doesnt make sense to test every function, test some If it doesnt make sense to test every function, test some 13Stroustrup/Programming

How to report an error Return an error value (not general, problematic) Return an error value (not general, problematic) int area(int length, int width) // return a negative value for bad input { if(length <=0 || width <= 0) return -1; return length*width; } So, let the caller beware So, let the caller beware int z = area(x,y); if (z<0) error("bad area computation"); // … Problems Problems What if I forget to check that return value? What if I forget to check that return value? For some functions there isnt a bad value to return (e.g. max()) For some functions there isnt a bad value to return (e.g. max()) 14Stroustrup/Programming

How to report an error Set an error status indicator (not general, problematic, dont!) Set an error status indicator (not general, problematic, dont!) int errno = 0;// used to indicate errors int area(int length, int width) { if (length<=0 || width<=0) errno = 7;// || means or return length*width; } So, let the caller check So, let the caller check int z = area(x,y); if (errno==7) error("bad area computation"); // … Problems Problems What if I forget to check errno? What if I forget to check errno? How do I pick a value for errno thats different from all others? How do I pick a value for errno thats different from all others? How do I deal with that error? How do I deal with that error? 15Stroustrup/Programming

How to report an error Report an error by throwing an exception Report an error by throwing an exception class Bad_area { }; // a class is a user defined type // Bad_area is a type to be used as an exception // Bad_area is a type to be used as an exception int area(int length, int width) { if (length<=0 || width<=0) throw Bad_area(); // note the () return length*width; } Catch and deal with the error (e.g., in main()) Catch and deal with the error (e.g., in main()) try { int z = area(x,y);// if area() doesnt throw an exception } // make the assignment and proceed catch(Bad_area) {// if area() throws Bad_area(), respond cerr << "oops! Bad area calculation – fix program\n"; } 16Stroustrup/Programming

Exceptions Exception handling is general Exception handling is general You cant forget about an exception: the program will terminate if someone doesnt handle it (using a try … catch) You cant forget about an exception: the program will terminate if someone doesnt handle it (using a try … catch) Just about every kind of error can be reported using exceptions Just about every kind of error can be reported using exceptions You still have to figure out what to do about an exception (every exception thrown in your program) You still have to figure out what to do about an exception (every exception thrown in your program) Error handling is never really simple Error handling is never really simple 17Stroustrup/Programming

Out of range Try this Try this vector v(10);// a vector of 10 ints, // each initialized to the default value, 0, // referred to as v[0].. v[9] for (int i = 0; i<v.size(); ++i) v[i] = i; // set values for (int i = 0; i<=10; ++i)// print 10 values (???) cout << "v[" << i << "] == " << v[i] << endl; vectors operator[ ] (subscript operator) reports a bad index (its argument) by throwing a Range_error if you use #include "std_lib_facilities.h" vectors operator[ ] (subscript operator) reports a bad index (its argument) by throwing a Range_error if you use #include "std_lib_facilities.h" The default behavior can differ The default behavior can differ 18Stroustrup/Programming

Exceptions – for now For now, just use exceptions to terminate programs gracefully, like this For now, just use exceptions to terminate programs gracefully, like this int main() try{ // … } catch (out_of_range&) {// out_of_range exceptions cerr << "oops – some vector index out of range\n"; } catch (…) {// all other exceptions cerr << "oops – some exception\n"; } 19Stroustrup/Programming

A function error() Here is a simple error() function as provided in std_lib_facilities.h Here is a simple error() function as provided in std_lib_facilities.h This allows you to print an error message by calling error() This allows you to print an error message by calling error() It works by disguising throws, like this: It works by disguising throws, like this: void error(string s) // one error string { throw runtime_error(s); } void error(string s1, string s2) // two error strings { error(s1 + s2); // concatenates } 20Stroustrup/Programming

Using error( ) Example Example cout << "please enter integer in range [1..10]\n"; int x = -1;// initialize with unacceptable value (if possible) cin >> x; if (!cin) // check that cin read an integer error("didnt get a value"); error("didnt get a value"); if (x < 1 || 10 < x)// check if value is out of range error("x is out of range"); error("x is out of range"); // if we get this far, we can use x with confidence 21Stroustrup/Programming

How to look for errors When you have written (drafted?) a program, itll have errors (commonly called bugs) When you have written (drafted?) a program, itll have errors (commonly called bugs) Itll do something, but not what you expected Itll do something, but not what you expected How do you find out what it actually does? How do you find out what it actually does? How do you correct it? How do you correct it? This process is usually called debugging This process is usually called debugging 22Stroustrup/Programming

Debugging How not to do it How not to do it while (program doesnt appear to work) { // pseudo code Randomly look at the program for something that looks odd Change it to look better } Key question Key question How would I know if the program actually worked correctly? 23Stroustrup/Programming

Program structure Make the program easy to read so that you have a chance of spotting the bugs Make the program easy to read so that you have a chance of spotting the bugs Comment Comment Explain design ideas Explain design ideas Use meaningful names Use meaningful names Indent Indent Use a consistent layout Use a consistent layout Your IDE tries to help (but it cant do everything) Your IDE tries to help (but it cant do everything) You are the one responsible You are the one responsible Break code into small functions Break code into small functions Try to avoid functions longer than a page Try to avoid functions longer than a page Avoid complicated code sequences Avoid complicated code sequences Try to avoid nested loops, nested if-statements, etc. Try to avoid nested loops, nested if-statements, etc. (But, obviously, you sometimes need those) Use library facilities Use library facilities 24Stroustrup/Programming

First get the program to compile Is every string literal terminated? Is every string literal terminated? cout << "Hello, << name << '\n'; // oops! Is every character literal terminated? Is every character literal terminated? cout << "Hello, " << name << '\n; // oops! Is every block terminated? Is every block terminated? if (a>0) { /* do something */ else { /* do something else */ } // oops! else { /* do something else */ } // oops! Is every set of parentheses matched? Is every set of parentheses matched? if (a// oops! x = f(y); x = f(y); The compiler generally reports this kind of error late The compiler generally reports this kind of error late It doesnt know you didnt mean to close it later It doesnt know you didnt mean to close it later 25Stroustrup/Programming

First get the program to compile Is every name declared? Is every name declared? Did you include needed headers? (e.g., std_lib_facilities.h ) Did you include needed headers? (e.g., std_lib_facilities.h ) Is every name declared before its used? Is every name declared before its used? Did you spell all names correctly? Did you spell all names correctly? int count;/* … */ ++Count;// oops! char ch;/* … */ Cin>>c;// double oops! Did you terminate each expression statement with a semicolon? Did you terminate each expression statement with a semicolon? x = sqrt(y)+2// oops! z = x+3; 26Stroustrup/Programming

Debugging Carefully follow the program through the specified sequence of steps Carefully follow the program through the specified sequence of steps Pretend youre the computer executing the program Pretend youre the computer executing the program Does the output match your expectations? Does the output match your expectations? If there isnt enough output to help, add a few debug output statements If there isnt enough output to help, add a few debug output statements cerr << "x == " << x << ", y == " << y << '\n'; Be very careful Be very careful See what the program specifies, not what you think it should say See what the program specifies, not what you think it should say Thats much harder to do than it sounds Thats much harder to do than it sounds for (int i=0; 0<month.size(); ++i) {// oops! for (int i=0; 0<month.size(); ++i) {// oops! for( int i = 0; i<=max; ++j) { // oops! (twice) for( int i = 0; i<=max; ++j) { // oops! (twice) 27Stroustrup/Programming

Debugging When you write the program, insert some checks (sanity checks) that variables have reasonable values When you write the program, insert some checks (sanity checks) that variables have reasonable values Function argument checks are prominent examples of this Function argument checks are prominent examples of this if (number_of_elements<0) error("impossible: negative number of elements"); if (largest_reasonable<number_of_elements) error("unexpectedly large number of elements"); if (x<y) error("impossible: x<y"); Design these checks so that some can be left in the program even after you believe it to be correct Design these checks so that some can be left in the program even after you believe it to be correct Its almost always better for a program to stop than to give wrong results Its almost always better for a program to stop than to give wrong results 28Stroustrup/Programming

Debugging Pay special attention to end cases (beginnings and ends) Pay special attention to end cases (beginnings and ends) Did you initialize every variable? Did you initialize every variable? To a reasonable value To a reasonable value Did the function get the right arguments? Did the function get the right arguments? Did the function return the right value? Did the function return the right value? Did you handle the first element correctly? Did you handle the first element correctly? The last element? The last element? Did you handle the empty case correctly? Did you handle the empty case correctly? No elements No elements No input No input Did you open your files correctly? Did you open your files correctly? more on this in chapter 11 more on this in chapter 11 Did you actually read that input? Did you actually read that input? Write that output? Write that output? 29Stroustrup/Programming

Debugging If you cant see the bug, youre looking in the wrong place If you cant see the bug, youre looking in the wrong place Its easy to be convinced that you know what the problem is and stubbornly keep looking in the wrong place Its easy to be convinced that you know what the problem is and stubbornly keep looking in the wrong place Dont just guess, be guided by output Dont just guess, be guided by output Work forward through the code from a place you know is right Work forward through the code from a place you know is right so what happens next? Why? so what happens next? Why? Work backwards from some bad output Work backwards from some bad output how could that possibly happen? how could that possibly happen? Once you have found the bug carefully consider if fixing it solves the whole problem Once you have found the bug carefully consider if fixing it solves the whole problem Its common to introduce new bugs with a quick fix Its common to introduce new bugs with a quick fix I found the last bug I found the last bug is a programmers joke is a programmers joke 30Stroustrup/Programming

Note Error handling is fundamentally more difficult and messy than ordinary code Error handling is fundamentally more difficult and messy than ordinary code There is basically just one way things can work right There is basically just one way things can work right There are many ways that things can go wrong There are many ways that things can go wrong The more people use a program, the better the error handling must be The more people use a program, the better the error handling must be If you break your own code, thats your own problem If you break your own code, thats your own problem And youll learn the hard way And youll learn the hard way If your code is used by your friends, uncaught errors can cause you to lose friends If your code is used by your friends, uncaught errors can cause you to lose friends If your code is used by strangers, uncaught errors can cause serious grief If your code is used by strangers, uncaught errors can cause serious grief And they may not have a way of recovering And they may not have a way of recovering 31Stroustrup/Programming

Pre-conditions What does a function require of its arguments? What does a function require of its arguments? Such a requirement is called a pre-condition Such a requirement is called a pre-condition Sometimes, its a good idea to check it Sometimes, its a good idea to check it int area(int length, int width) // calculate area of a rectangle // length and width must be positive { if (length<=0 || width <=0) throw Bad_area(); return length*width; } 32Stroustrup/Programming

Post-conditions What must be true when a function returns? What must be true when a function returns? Such a requirement is called a post-condition Such a requirement is called a post-condition int area(int length, int width) // calculate area of a rectangle // length and width must be positive { if (length<=0 || width <=0) throw Bad_area(); // the result must be a positive int that is the area // no variables had their values changed return length*width; } 33Stroustrup/Programming

Pre- and post-conditions Always think about them Always think about them If nothing else write them as comments If nothing else write them as comments Check them where reasonable Check them where reasonable Check a lot when you are looking for a bug Check a lot when you are looking for a bug This can be tricky This can be tricky How could the post-condition for area() fail after the pre- condition succeeded (held)? How could the post-condition for area() fail after the pre- condition succeeded (held)? 34Stroustrup/Programming

Testing How do we test a program? How do we test a program? Be systematic Be systematic pecking at the keyboard is okay for very small programs and for very initial tests, but is insufficient for real systems pecking at the keyboard is okay for very small programs and for very initial tests, but is insufficient for real systems Think of testing and correctness from the very start Think of testing and correctness from the very start When possible, test parts of a program in isolation When possible, test parts of a program in isolation E.g., when you write a complicated function write a little program that simply calls it with a lot of arguments to see how it behaves in isolation before putting it into the real program E.g., when you write a complicated function write a little program that simply calls it with a lot of arguments to see how it behaves in isolation before putting it into the real program Well return to this question in Chapter 26 Well return to this question in Chapter 26 35Stroustrup/Programming

The next lecture In the next two lectures, well discuss the design and implementation of a complete small program – a simple desk calculator. In the next two lectures, well discuss the design and implementation of a complete small program – a simple desk calculator. 36Stroustrup/Programming