blob: 5a31940351a369c3c416b1469d508c48b8a5bd7d [file] [log] [blame]
Benny Prijono5dcb38d2005-11-21 01:55:47 +00001/* $Id$ */
2/*
3 * Copyright (C)2003-2006 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
24/**
25 * \page page_pjlib_samples_except_c Example: Exception Handling
26 *
27 * Below is sample program to demonstrate how to use exception handling.
28 *
29 * \includelineno pjlib-samples/except.c
30 */
31
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{
50 PJ_USE_EXCEPTION;
51
52 PJ_TRY {
53 void *data = my_malloc(200);
54 free(data);
55 randomly_throw_exception();
56 }
Benny Prijonod0d44f52005-11-21 16:57:02 +000057 PJ_CATCH_ANY {
Benny Prijono5dcb38d2005-11-21 01:55:47 +000058 pj_exception_id_t x_id;
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