Exceptions

Defensive Programming

The question isn’t whether or not we will make programming errors...

the question is whether or not we will arrange for our compiler and tools to help us find them.

  • Sutter & Alexandrescu, C++ Coding Standards

Possible Failures

Code can go wrong in various ways:

  1. Errors in your code - you did this!
    • bugs, invariant violation, exposure of data representation
  2. Misuse of your code - 1D-10T User Error
    • client-code violations of your preconditions
  3. External problems - you can't control this!
    • non existent input file, inappropriate file permissions
    • out of memory, memory corruption
    • hardware limitations (overflow, underflow)

Assertions

Use assertions to document and check assumptions. i.e: include <cassert> + assert(<boolean expression>);

  • Check preconditions of functions.
  • Check postconditions of functions.
  • Check representation invariants (next week’s lectures).
  • Check postconditions of called functions.

Goal: Abort program as close to error as possible, then can use debugger to examine program state.

Assertions in Production Code?

It depends: Yes: don’t want to risk the program corrupting persistent data. No: may need program to keep executing; maybe bug doesn’t have that many bad consequences.

You can remove all assertions by compiling with preprocessor variable NDEBUG defined: % g++ -DNDEBUG . . .

Warning: Assertions should not have side effects! i.e: assert (i++ == 10);

- program behaves differently if asserts are defined!

Traditional Error Handling Mechanisms (EHMs)

  • Global vars that contain error messages
  • Return values

Issues:

  • these are passive checks, and cannot _force _the programmer to check values
  • global vars won't work with parallel code
  • mixes "normal" execution with "error handling"
    • it's everywhere since one has to check for errors all the time (assuming a naiive unmodularized implementation)
  • In the industry, ~50% of code (if not more) is just error-handling code!

Code-heavy section, see slides!

results matching ""

    No results matching ""