WARNING: The online documentation has moved to https://docs.pjsip.org.

Visit the new documentation at https://docs.pjsip.org:

BLOG | DOCUMENTATION | GITHUB

Home --> Documentations --> PJLIB Reference

Example: Exception Handling

Below is sample program to demonstrate how to use exception handling.

1/*
2 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
3 * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19#include <pj/except.h>
20#include <pj/rand.h>
21#include <stdio.h>
22#include <stdlib.h>
23
32static pj_exception_id_t NO_MEMORY, OTHER_EXCEPTION;
33
34static void randomly_throw_exception()
35{
36 if (pj_rand() % 2)
37 PJ_THROW(OTHER_EXCEPTION);
38}
39
40static void *my_malloc(size_t size)
41{
42 void *ptr = malloc(size);
43 if (!ptr)
44 PJ_THROW(NO_MEMORY);
45 return ptr;
46}
47
48static int test_exception()
49{
51
52 PJ_TRY {
53 void *data = my_malloc(200);
54 free(data);
55 randomly_throw_exception();
56 }
59
60 x_id = PJ_GET_EXCEPTION();
61 printf("Caught exception %d (%s)\n",
62 x_id, pj_exception_id_name(x_id));
63 }
64 PJ_END
65 return 1;
66}
67
68int main()
69{
70 pj_status_t rc;
71
72 // Error handling is omited for clarity.
73
74 rc = pj_init();
75
76 rc = pj_exception_id_alloc("No Memory", &NO_MEMORY);
77 rc = pj_exception_id_alloc("Other Exception", &OTHER_EXCEPTION);
78
79 return test_exception();
80}
81
Exception Handling in C.
#define PJ_CATCH_ANY
Definition: except.h:388
#define PJ_TRY
Definition: except.h:373
#define PJ_THROW(exception_id)
Definition: except.h:402
#define PJ_GET_EXCEPTION()
Definition: except.h:409
#define PJ_END
Definition: except.h:394
#define PJ_USE_EXCEPTION
Definition: except.h:367
pj_status_t pj_init(void)
int pj_status_t
Definition: types.h:68
int pj_exception_id_t
Definition: types.h:276
const char * pj_exception_id_name(pj_exception_id_t id)
pj_status_t pj_exception_id_alloc(const char *name, pj_exception_id_t *id)
int pj_rand(void)
Random Number Generator.

 


PJLIB Open Source, high performance, small footprint, and very very portable framework
Copyright (C) 2006-2009 Teluu Inc.