except.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. /**
  24. * \page page_pjlib_samples_except_c Example: Exception Handling
  25. *
  26. * Below is sample program to demonstrate how to use exception handling.
  27. *
  28. * \includelineno pjlib-samples/except.c
  29. */
  30. static pj_exception_id_t NO_MEMORY, OTHER_EXCEPTION;
  31. static void randomly_throw_exception()
  32. {
  33. if (pj_rand() % 2)
  34. PJ_THROW(OTHER_EXCEPTION);
  35. }
  36. static void *my_malloc(size_t size)
  37. {
  38. void *ptr = malloc(size);
  39. if (!ptr)
  40. PJ_THROW(NO_MEMORY);
  41. return ptr;
  42. }
  43. static int test_exception()
  44. {
  45. PJ_USE_EXCEPTION;
  46. PJ_TRY {
  47. void *data = my_malloc(200);
  48. free(data);
  49. randomly_throw_exception();
  50. }
  51. PJ_CATCH_ANY {
  52. pj_exception_id_t x_id;
  53. x_id = PJ_GET_EXCEPTION();
  54. printf("Caught exception %d (%s)\n",
  55. x_id, pj_exception_id_name(x_id));
  56. }
  57. PJ_END
  58. return 1;
  59. }
  60. int main()
  61. {
  62. pj_status_t rc;
  63. // Error handling is omited for clarity.
  64. rc = pj_init();
  65. rc = pj_exception_id_alloc("No Memory", &NO_MEMORY);
  66. rc = pj_exception_id_alloc("Other Exception", &OTHER_EXCEPTION);
  67. return test_exception();
  68. }