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

5_errors

  • Upload
    ameer

  • View
    218

  • Download
    2

Embed Size (px)

DESCRIPTION

school work document

Citation preview

  • Chapter 5ErrorsBjarne Stroustrupwww.stroustrup.com/Programming

  • AbstractWhen 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.*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • OverviewKinds of errorsArgument checkingError reportingError detectionExceptionsDebuggingTesting*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Errors I realized that from now on a large part of my life would be spent finding and correcting my own mistakes.Maurice Wilkes, 1949When we write programs, errors are natural and unavoidable; the question is, how do we deal with them?Organize software to minimize errors.Eliminate most of the errors we made anyway.DebuggingTestingMake 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.You can do much better for small programs. or worse, if youre sloppy*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Your ProgramShould produce the desired results for all legal inputsShould give reasonable error messages for illegal inputsNeed not worry about misbehaving hardwareNeed not worry about misbehaving system softwareIs 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.*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Sources of errorsPoor specificationWhats this supposed to do?Incomplete programsbut Ill not get around to doing that until tomorrowUnexpected argumentsbut sqrt() isnt supposed to be called with -1 as its argumentUnexpected inputbut the user was supposed to input an integerCode that simply doesnt do what it was supposed to doso fix it!*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Kinds of ErrorsCompile-time errorsSyntax errorsType errorsLink-time errorsRun-time errorsDetected by computer (crash)Detected by library (exceptions)Detected by user codeLogic errorsDetected by programmer (code runs, but produces incorrect output)*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Check your inputsBefore trying to use an input value, check that it meets your expectations/requirementsFunction argumentsData from input (istream)*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Bad function argumentsThe compiler helps:Number and types of arguments must match

    int area(int length, int width){return length*width;}

    int x1 = area(7); // error: wrong number of argumentsint x2 = area("seven", 2);// error: 1st argument has a wrong typeint x3 = area(7, 10);// okint x5 = area(7.5, 10);// ok, but dangerous: 7.5 truncated to 7;// most compilers will warn youint x = area(10, -7); // this is a difficult case: // the types are correct,// but the values make no sense*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Bad Function ArgumentsSo, how aboutint x = area(10, -7);?AlternativesJust dont do thatRarely a satisfactory answerThe caller should checkHard to do systematicallyThe function should checkReturn an error value (not general, problematic)Set an error status indicator (not general, problematic dont do this)Throw an exceptionNote: sometimes we cant change a function that handles errors in a way we do not likeSomeone else wrote it and we cant or dont want to change their code*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Bad function argumentsWhy worry?You want your programs to be correctTypically the writer of a function has no control over how it is calledWriting do it this way in the manual (or in comments) is no solution many people dont read manualsThe beginning of a function is often a good place to checkBefore the computation gets complicatedWhen to worry?If it doesnt make sense to test every function, test some*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • How to report an errorReturn an error value (not general, problematic)int area(int length, int width) // return a negative value for bad input{if(length
  • How to report an errorSet an error status indicator (not general, problematic, dont!)int errno = 0;// used to indicate errorsint area(int length, int width){if (length
  • How to report an errorReport an error by throwing an exceptionclass Bad_area { }; // a class is a user defined type // Bad_area is a type to be used as an exception

    int area(int length, int width){if (length

  • ExceptionsException handling is generalYou 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 exceptionsYou still have to figure out what to do about an exception (every exception thrown in your program)Error handling is never really simple

    *Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Out of rangeTry thisvector 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
  • Exceptions for nowFor now, just use exceptions to terminate programs gracefully, like this

    int main()try{ // }catch (out_of_range&) {// out_of_range exceptions cerr

  • A function error()Here is a simple error() function as provided in std_lib_facilities.hThis allows you to print an error message by calling error() 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}

    *Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Using error( )Examplecout > x;if (!cin) // check that cin read an integer error("didnt get a value");if (x < 1 || 10 < x)// check if value is out of range error("x is out of range");// if we get this far, we can use x with confidence*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

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

    Stroustrup/Programming/2015

  • DebuggingHow not to do itwhile (program doesnt appear to work) { // pseudo codeRandomly look at the program for something that looks oddChange it to look better}

    Key questionHow would I know if the program actually worked correctly?*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Program structureMake the program easy to read so that you have a chance of spotting the bugsCommentExplain design ideasUse meaningful namesIndentUse a consistent layoutYour IDE tries to help (but it cant do everything)You are the one responsibleBreak code into small functionsTry to avoid functions longer than a pageAvoid complicated code sequencesTry to avoid nested loops, nested if-statements, etc.(But, obviously, you sometimes need those)Use library facilities*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • First get the program to compileIs every string literal terminated?cout
  • First get the program to compile

    Is every name declared?Did you include needed headers? (e.g., std_lib_facilities.h)

    Is every name declared before its used?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?x = sqrt(y)+2// oops!z = x+3;*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • DebuggingCarefully follow the program through the specified sequence of stepsPretend youre the computer executing the programDoes the output match your expectations?If there isnt enough output to help, add a few debug output statementscerr
  • DebuggingWhen you write the program, insert some checks (sanity checks) that variables have reasonable valuesFunction argument checks are prominent examples of this

    if (number_of_elements

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

    Stroustrup/Programming/2015

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

    Stroustrup/Programming/2015

  • NoteError handling is fundamentally more difficult and messy than ordinary codeThere is basically just one way things can work rightThere are many ways that things can go wrongThe more people use a program, the better the error handling must beIf you break your own code, thats your own problemAnd youll learn the hard wayIf your code is used by your friends, uncaught errors can cause you to lose friendsIf your code is used by strangers, uncaught errors can cause serious griefAnd they may not have a way of recovering*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • Pre-conditionsWhat does a function require of its arguments?Such a requirement is called a pre-conditionSometimes, 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

  • Post-conditionsWhat must be true when a function returns?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

  • Pre- and post-conditionsAlways think about themIf nothing else write them as commentsCheck them where reasonableCheck a lot when you are looking for a bugThis can be trickyHow could the post-condition for area() fail after the pre-condition succeeded (held)?*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • TestingHow do we test a program?Be systematicpecking at the keyboard is okay for very small programs and for very initial tests, but is insufficient for real systemsThink of testing and correctness from the very startWhen possible, test parts of a program in isolationE.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 (this is typically called unit testing)Well return to this question in Chapter 26*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

  • The next lectureIn the next two lectures, well discuss the design and implementation of a complete small program a simple desk calculator.*Stroustrup/Programming/2015

    Stroustrup/Programming/2015

    *