Error handling

Author:
Jan Wedekind (jan at wedesoft.de)
Date:
Mon Dec 06 19:17:00 BST 2004

Introduction

There are several types of errors and several approaches how to deal with them therefore. Sometimes it is not easy to categorize an error, as the context for reusable code may change. However usually it is possible to categorize the following approaches:

Static Assertions

Static assertions are used for dealing with implementation errors, which are detectable during compile time. The boost-library offers a good tool for implementing static assertions.
    #include <climits>
    #include <cwchar>
    #include <boost/static_assert.hpp>

    namespace my_conditions {
    
    BOOST_STATIC_ASSERT(sizeof(int) * CHAR_BIT >= 32);
    BOOST_STATIC_ASSERT(WCHAR_MIN >= 0);
    
    } // namespace my_conditions
(This piece of code was taken from the boost-library's documentation).

Dynamic Assertions

Dynamic assertions are used for enforcing pre- and post-conditions during run-time. Dynamic assertions are only checked, when the code is compiled without the -DNDEBUG-option. That's why they only should be used to test against implementation errors.
    #include <cassert>
    #include <iostream>

    using namespace std;

    int iabs( int x ) {
       int retVal = x > 0 ? x : -x;
       assert( x >= 0 );
       return retVal;
    }

    int main(void)
    {
       cerr << "|-3| = " << iabs( -3 ) << endl;
       return 0;
    }

Exception Handling

Handling of Run-Time-Errors

Advantages

Exceptions are used to handle run-time errors. Exception handling has the following advantages: For a code-example see mm_exception.
See also:
mimas::mm_exception

Consistency with older code

Return values.

Still a lot of code (f.e. the standard C-library) is not using exceptions. Very often one has to convert a return-value to an exception. Here is an example with a fictive exception-class: OutOfMemory.
    void *mem = malloc( 1000 );
    if ( mem == NULL ) throw OutOfMemory( "mem", 1000 );

Object states.

Staying consistent with the I/O-stream design f.e. forbids throwing exceptions in >>- and <<-operators. The program using the stream rather has to check for the stream's state (and may throw an exception).
    #include <iostream>
    
    using namespace std;
    
    int main(void)
    {
        bool b = false;
        if ( cin >> b )
           cout << b << endl;
        return 0;
    }

[GNU/Linux] [Qt] [Mesa] [STL] [Lapack] [Boost] [Magick++] [Xalan-C and Xerces-C] [doxygen] [graphviz] [FFTW] [popt] [xine] [Gnuplot] [gnu-arch] [gcc] [gstreamer] [autoconf/automake/make] [freshmeat.net] [opensource.org] [sourceforge.net] [MMVL]
mimas 2.1 - Copyright Mon Oct 30 11:31:17 2006, Bala Amavasai, Stuart Meikle, Arul Selvan, Fabio Caparrelli, Jan Wedekind, Manuel Boissenin, ...