CSCE 121 Chapter 5
Jump to navigation
Jump to search
« previous | Monday, September 6, 2010 | next »
Philosophy of Program Correctiveness
A program should:
- produce desired results for all legal inputs
- give reasonable error messages for all illegal inputs
- not worry about malfunctioning hardware or other software
- 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;
}
- & after exception type declaration means "pass the exception by reference"
- cerr is just like cout, except it's used for error messages.
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.