2012年1月9日 星期一

[C++] Exception-safe code



Some guide

Exception-safe definition:
- Basic
    invariants and no resource are leaked
- Strong
    operations has either completed successfully or throw exception leaving program
    state exactlyly as it was before the operation started
- No-throw
    operation will not emit an exception

Exception guide line:
- Throw by value
- Catch by reference
- no exception specification
                                                                                                                                                                                                           
* function can not template partial specialization

Some code example:

#include <iostream>     
void foo() throw ()
{                  
    // it will cause abort 
    // because it throw when the exception specification said NO
    throw(1);      
}                  
                   
void goo()         
{                  
    try {          
        int a = 1; 
        throw(1);  
    } catch(...) { 
        // this will cause abort too 
        // because you can not rethrow in catch statement
        throw;     
    }              
}                  
                   
/*                 
 * The following is the C API for C++ library pattern to handle exception
 */                
                   
int getReturnCodeFromException()
{                  
    try {          
        // rethrow 
        throw;     
    } catch(int a) 
    {              
        return -1; 
    } catch(double b)
    {              
        return -2; 
    }              
    // for each type of exception, you can create different return code
    // ...         
}                  
void cppAPI1()
{           
    throw (1);
}           
            
            
void cppAPI2()
{           
    throw (1.12);
}           
            
int cAPI1() 
{           
    try {   
        cppAPI1();
    } catch(...) {                           
        int rc = getReturnCodeFromException();
        return rc;
    }       
}           
            
int cAPI2() 
{           
    try {   
        cppAPI2();
    } catch(...) {                           
        int rc = getReturnCodeFromException();
        return rc;
    }       
}           
            
int main()  
{           
//    foo();
//    goo();
    std::cout << "cAPI1 rc = " << cAPI1() << std::endl;
    std::cout << "cAPI2 rc = " << cAPI2() << std::endl;
    return 0;
}                                
Reference http://exceptionsafecode.com/