BLOG | DOCUMENTATION | TRAC

Home --> Documentations --> PJLIB Reference

Example: Exception Handling

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

00001 /* $Id: except.c 3553 2011-05-05 06:14:19Z nanang $ */
00002 /* 
00003  * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
00004  * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
00005  *
00006  * This program is free software; you can redistribute it and/or modify
00007  * it under the terms of the GNU General Public License as published by
00008  * the Free Software Foundation; either version 2 of the License, or
00009  * (at your option) any later version.
00010  *
00011  * This program is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014  * GNU General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU General Public License
00017  * along with this program; if not, write to the Free Software
00018  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
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     // Error handling is omited for clarity.
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 

 


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