Beruflich Dokumente
Kultur Dokumente
Errors
Bjarne Stroustrup
www.stroustrup.com/Programming
Abstract
Overview
Kinds of errors
Argument checking
Error reporting
Error detection
Exceptions
Debugging
Testing
Stroustrup/Programming/2015
Errors
Debugging
Testing
Stroustrup/Programming/2015
Your Program
1.
2.
3.
4.
5.
Stroustrup/Programming/2015
Sources of errors
Poor specification
Incomplete programs
Unexpected input
Unexpected arguments
so fix it!
Stroustrup/Programming/2015
Kinds of Errors
Compile-time errors
Link-time errors
Run-time errors
Syntax errors
Type errors
Logic errors
Stroustrup/Programming/2015
Function arguments
Data from input (istream)
Stroustrup/Programming/2015
Hard to do systematically
Someone else wrote it and we cant or dont want to change their code
Stroustrup/Programming/2015
10
Why worry?
When to worry?
Stroustrup/Programming/2015
11
Problems
12
Problems
13
14
Exceptions
Stroustrup/Programming/2015
15
Out of range
Try this
vector<int> 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;
16
17
A function error()
Stroustrup/Programming/2015
18
Using error( )
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");
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
19
Stroustrup/Programming/2015
20
Debugging
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
How would I know if the program actually worked correctly?
Stroustrup/Programming/2015
21
Program structure
Comment
22
// oops!
23
// oops!
// oops!
Stroustrup/Programming/2015
24
Debugging
Be very careful
// oops!
// oops! (twice)
25
Debugging
Its almost always better for a program to stop than to give wrong
results
Stroustrup/Programming/2015
26
Debugging
No elements
No input
To a reasonable value
27
Debugging
Work forward through the code from a place you know is right
is a programmers joke
Stroustrup/Programming/2015
28
Note
The more people use a program, the better the error handling
must be
Stroustrup/Programming/2015
29
Pre-conditions
Stroustrup/Programming/2015
30
Post-conditions
31
How could the post-condition for area() fail after the precondition succeeded (held)?
Stroustrup/Programming/2015
32
Testing
Be systematic
Stroustrup/Programming/2015
33
Stroustrup/Programming/2015
34