Below is sample program to demonstrate how to use exception handling.
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #include <pj/except.h>
00021 #include <pj/rand.h>
00022 #include <stdio.h>
00023 #include <stdlib.h>
00024
00033 static pj_exception_id_t NO_MEMORY, OTHER_EXCEPTION;
00034
00035 static void randomly_throw_exception()
00036 {
00037 if (pj_rand() % 2)
00038 PJ_THROW(OTHER_EXCEPTION);
00039 }
00040
00041 static void *my_malloc(size_t size)
00042 {
00043 void *ptr = malloc(size);
00044 if (!ptr)
00045 PJ_THROW(NO_MEMORY);
00046 return ptr;
00047 }
00048
00049 static int test_exception()
00050 {
00051 PJ_USE_EXCEPTION;
00052
00053 PJ_TRY {
00054 void *data = my_malloc(200);
00055 free(data);
00056 randomly_throw_exception();
00057 }
00058 PJ_CATCH_ANY {
00059 pj_exception_id_t x_id;
00060
00061 x_id = PJ_GET_EXCEPTION();
00062 printf("Caught exception %d (%s)\n",
00063 x_id, pj_exception_id_name(x_id));
00064 }
00065 PJ_END
00066 return 1;
00067 }
00068
00069 int main()
00070 {
00071 pj_status_t rc;
00072
00073
00074
00075 rc = pj_init();
00076
00077 rc = pj_exception_id_alloc("No Memory", &NO_MEMORY);
00078 rc = pj_exception_id_alloc("Other Exception", &OTHER_EXCEPTION);
00079
00080 return test_exception();
00081 }
00082