try, finally

Jason Cipriani jason.cipriani@gmail.com
Wed Mar 19 16:13:00 GMT 2008


Does GCC have anything similar to the MS and Borland compiler's __try
and __finally keywords? When using GCC I often find that I have code
like this (a moderately complex, and highly contrived, example):

====

  void *data1 = NULL, *data2 = NULL, *data3 = NULL;

  try {

    if (!(data1 = malloc(1000)))
      throw Something();
    if (!(data2 = malloc(1000)))
      throw Something();
    if (!(data3 = malloc(1000)))
      throw Something();

  } catch (...) {

    // cleanup code
    free(data3);
    free(data2);
    free(data1);
    throw;

  }

  // the same cleanup code
  free(data3);
  free(data2);
  free(data1);

===

Where I am duplicating cleanup code for normal returns and exception
handling, but what I really want to do is something like this:

===

void *data1 = NULL, *data2 = NULL, *data3 = NULL;

__try {

  if (!(data1 = malloc(1000)))
    throw Something();
  if (!(data2 = malloc(1000)))
    throw Something();
  if (!(data3 = malloc(1000)))
    throw Something();

  // do stuff

} __finally {

  // cleanup code
  free(data3);
  free(data2);
  free(data1);

}

===

Thanks,
Jason



More information about the Gcc-help mailing list