simple header files for enable try-catch in c lang.
and it also has utility macros.
-
including a header file(ctry.h).
-
implements err_callback function.(please see 'erorr callback function' section)
__ck_throwerr("set error message");try {
/* pros */
} catch {
/* err pros */
}please change FAILED_VAL to any error value depending on function return value.
try {
/* pros */
} catch(FAILED_VAL) {
/* err pros */
}please use 'catch_' macro with or without return value.
try {
/* pros */
} catch_ {
/* err pros */
} finally {
/* pros */
}please use '$' instead of ';' when you called function.
'$' is macro for check whether function call threw error.
try {
call_func()$
} catch {
/* err pros */
}you can get error message setted by __ck_throwerr by using CK_ERROR_MSG define.
try {
__ck_throwerr("error message");
} catch {
printf("%s¥n", CK_ERROR_MSG); // error message
}error callback function is called every time it threw error.
it is necessary you to implements.
please chenge value of CK_ERRCB_FUNCNAME in hdr/ctry/check.h, if you want rename function name
/* prototype */
/**
* error calback function
*
* @param file name of error point (__FILE__)
* @param line number of error point (__LINE__)
* @param error message
*/
void err_callback (const char *, int, char *);#include <stdio.h>
#include "ctry.h"
void err_callback (const char *fn, int ln, char *msg) {
NULCHK_SKIP(fn);
NULCHK_SKIP(msg);
printf("%s,%d:%s\n", fn, ln, msg);
}
void test_func (int val) {
try {
if (100 > val) {
__ck_throwerr("test error");
}
} catch {
__ck_throwerr("test in catch error");
}
}
int main (void) {
try {
test_func(200)$
test_func(10)$
return 0;
} catch_ret (-1) {
printf("%s\n", CK_ERROR_MSG);
return -1;
}
}result:
main.c,13:test error
main.c,16:test in catch error
test in catch error
this try-catch refers the global value and use the single label.
please be aware of the following.
- not supported multi-process, multi-thread.
- not supported nest try-catch
- default error message buffer size is 256.