CSCE 121 Chapter 5

From Notes
Jump to navigation Jump to search

« previous | Monday, September 6, 2010 | next »

Philosophy of Program Correctiveness

A program should:

  1. produce desired results for all legal inputs
  2. give reasonable error messages for all illegal inputs
  3. not worry about malfunctioning hardware or other software
  4. be allowed to terminate upon finding an error

Exceptions

void error(string msg) {
  throw runtime_error(msg);
}
...
int main()
try {
  ... // if something calls error() function, then catch will run.
} catch (runtime_error& e) {
  cerr << "runtime_error: " << e.what() << endl;
  return 1;
}


To catch ALL exceptions, use the following code:

try {
  ...
} catch (exception& e) {
  cerr << "error: " << e.what() << endl;
}
  • exception is the generic exception class


Wednesday, September 8, 2010

Code Structure

  • Comments/documentation
  • meaningful names
  • Indentation
  • Small functions
  • Use libraries where available

Debugging

  • test as often as necessary
  • don't "quick-fix"

Logically structuring functions can eliminate bugs in the future:

Pre-conditions
Think: What does a function require of its arguments?
Check them at beginning of function before using them
Post-conditions
sanity-check for return values (e.g. check for negative area)

Testing

Try to break your own application. Be as stupid as possible to simulate every type of error imaginable.