blob: 3bbfa544253833473259dc34e7b6892ea1e2cecb [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 }
57 PJ_CATCH( NO_MEMORY ) {
58 puts("Can't allocate memory");
59 return 0;
60 }
61 PJ_DEFAULT {
62 pj_exception_id_t x_id;
63
64 x_id = PJ_GET_EXCEPTION();
65 printf("Caught exception %d (%s)\n",
66 x_id, pj_exception_id_name(x_id));
67 }
68 PJ_END
69 return 1;
70}
71
72int main()
73{
74 pj_status_t rc;
75
76 // Error handling is omited for clarity.
77
78 rc = pj_init();
79
80 rc = pj_exception_id_alloc("No Memory", &NO_MEMORY);
81 rc = pj_exception_id_alloc("Other Exception", &OTHER_EXCEPTION);
82
83 return test_exception();
84}
85