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.
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 |