Programming Principles & Practice Using C++

BS.5 Errors

Should we check for errors when we call a function or within the function called (callee)?

Within the callee! Fewer checks! Less brittle!

How should we report errors when we find them?

Return a bad value? No! Then we would have to check for it whenever the function is called!


BY 'Unknown Author'
ON '2016-11-01T17:07:59'
NOTE: 'class Bad_area{};'
NOTE: 'int area(int length, int width) {'
NOTE: '        if (length<=0 || width<=0) throw Bad_area{};'
NOTE: '        return length * width;'
NOTE: '}']
Exceptions! Throw an exception when there is an error: Either the calling code catches it and deals with it, or the program terminates and reports the exception.

Bad input is detected by following up a cin >> call with an if (!cin) as this checks whether the last cin call was successful.

If you throw runtime_error(str) then the message for the caught error can be accessed at e.what()

When we catch errors we have to "pass the exception by reference" like catch(exception& e)

BY 'Unknown Author'
ON '2016-11-01T17:10:05'
NOTE: 'Alternative for-loop syntax;'
NOTE: 'for(int i; cin >> i;)'
NOTE: 'for (int number : numbers)']

Use pre-conditions (check that input is sane) and post-conditions (check that output is sane)

BS.6 Writing a Program