exc_test.c 2.67 KB
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <scot/exception.h>
#include <scot_common.h>

#define     OPEN_FAILED    0
#define     CLOSE_FAILED   1
#define     WARNING1       2
#define     WARNING2       3
#define     WARNING3       4
#define     WARNING4       5
#define     ERROR1         6
#define     ERROR2         7

const char *errmsg[] = {
   N_("Failed to open the file."),
   N_("Failed to close the file."),
   N_("This is WARNING no. 1"),
   N_("This is WARNING no. 2"),
   N_("This is WARNING no. 3"),
   N_("This is WARNING no. 4"),
   N_("This is ERROR no. 1"),
   N_("This is ERROR no. 2"),
   NULL
};

/* 
 * a simple test case
 */
void
testf2 (void)
{
   THROW (EXC (EXC_WARNING, WARNING3, D_(errmsg [WARNING3])));
   THROW (EXC (EXC_ERROR,   ERROR2,   D_(errmsg [ERROR2])));
   THROW (EXC (EXC_WARNING, WARNING4, D_(errmsg [WARNING4])));
}

void
testf (void)
{
   excenv_t *ee;

   TRY
      testf2 ();
   CATCH (ee)
   {
      forward_all_exceptions (ee);

      THROW (EXC (EXC_WARNING, WARNING1, D_(errmsg [WARNING1])));
      // THROW (EXC (EXC_ERROR,   ERROR1,   D_(errmsg [ERROR1])));
      THROW (EXC (EXC_WARNING, WARNING2, D_(errmsg [WARNING2])));
   }
}

FILE *
exc_fopen (const char *path, const char *mode)
{
   excenv_t *ee;
   FILE     *fptr;

   TRY
      if ((fptr = fopen (path, mode)) == NULL)
         THROW (EXC (EXC_ERROR, errno, strerror (errno)));
   CATCH (ee)
   {
      forward_all_exceptions (ee);
      THROW (EXC (EXC_ERROR, OPEN_FAILED, D_(errmsg[OPEN_FAILED])));
   }

   return fptr;
}

int
exc_fclose (FILE *fptr)
{
   excenv_t *ee;
   int      ret;

   TRY
      if ((ret = fclose (fptr)) != 0)
         THROW (EXC (EXC_ERROR, errno, strerror (errno)));
   CATCH (ee)
   {
      forward_all_exceptions (ee);
      THROW (EXC (EXC_ERROR, CLOSE_FAILED, D_(errmsg[CLOSE_FAILED])));
   }

   return ret;
}

int
main (void) {
   excenv_t *ee;
   char     *locale;
   char     fname[] = "./exc_test.fil";
   FILE     *fptr;

   locale = setlocale (LC_ALL, "");

   TRY
   {
      fptr = exc_fopen (fname, "w+");
      testf ();
      exc_fclose (fptr);
   }
   CATCH (ee)
   {
      exception_t *e;

      while (e = retrive_exception (ee))
      {
         if (EXC_IN_THIS_TRY (e))
         {
            switch (exc_errnum_get (e))
            {
               case CLOSE_FAILED:
                  /* here we do something for previous cleanups... */
                  fprintf (stderr, "an open FILE* remains\n");
               case ERROR1:
                  fclose (fptr);
            }
         }

         print_exception (e);
			free_exception (e);
      }

      free_catched (ee);
   }
   /*   print_all_exceptions (ee); */

   exc_end ();

   return 0;
}