1.2.6 Error and Exception Handling

Origin C supports C++ exception handling using the try, catch, and throw statements.

The try block consists of the try keyword followed by one or more statements enclosed in braces. Immediately after the try block is the catch handler. Origin C supports only a single catch handler that accepts an integer argument. After the catch keyword comes one or more statements enclosed in braces.

try
{
    LPSTR lpdest = NULL;    // NULL pointer on purpose
    strcpy(lpdest, "Test"); // copy to NULL pointer to cause error
}
catch(int nErr)
{
    out_int("Error = ", nErr);
}

The try-catch works by executing the statements in the try block. If an error occurs, the execution will jump to the catch block. If no error occurs then the catch block is ignored.

The throw keyword is optional and is used to trigger an error and cause execution to jump to the catch block.

void TryCatchThrowEx()
{
    try
    {
        DoSomeWork(4);  // pass a valid number to show success
        DoSomeWork(-1); // pass an invalid number to cause error
    }
    catch(int iErr)
    {
        printf("Error code = %d\n", iErr);
    }
} 
void DoSomeWork(double num)
{
    if( num < 0 )
        throw 100; // Force error
    if( 0 == num )
        throw 101; // Force error

    double result = sqrt(num) / log(num);
    printf("sqrt(%f) / log(%f) = %g\n", num, num, result); 
}