1.2.6 Error and Exception Handling


Exception Handling

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

A try block is the keyword try followed by statements in braces. Immediately after the try block is a single catch handler.

    • Note:** Origin C supports only **one** catch handler and it must accept an int error code.
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);
}

During execution, statements in the try block run first. If an error is thrown, control jumps to the catch block; otherwise the catch block is skipped.

You can use throw to signal an error explicitly and jump to the catch block:

void TryCatchThrowEx()
{
    try
    {
        DoSomeWork(4);   // valid -> prints result
        DoSomeWork(-1);  // invalid -> throws
    }
    catch (int iErr)
    {
        printf("Error code = %d\n", iErr);
    }
}

void DoSomeWork(double num)
{
    if ( num < 0 )
        throw 100; // force error: negative input
    if ( 0 == num )
        throw 101; // force error: zero not allowed

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

Because only catch(int) is supported, choose and document distinct integer codes for different error conditions.