[bind10-dev] whether/when to use exceptions

Christos Zoulas christos at zoulas.com
Wed Oct 14 12:44:09 UTC 2009


On Oct 14,  1:30pm, shane at isc.org (Shane Kerr) wrote:
-- Subject: Re: [bind10-dev] whether/when to use exceptions

| An example:
|         
|         fp = fopen("foo.txt", "w");
|         if (fp == NULL) {
|             return ERROR_CODE;
|         }
|         for (i=0; i<10; i++) {
|             if (fprintf(fp, "%d\n", i) < 0) {
|                 fclose(fp);
|                 remove("foo.txt");
|                 return ERROR_CODE;
|             }
|         }
|         if (fclose(fp) != 0) {
|             remove("foo.txt");
|             return ERROR_CODE;
|         }
|         return SUCCESS_CODE;
| 
| Contrast with:
| 
|         try:
|             fp = open("bar.txt", "w")
|             for i in range(10):
|                 fp.write("%d\n" % I)
|             fp.close()
|             return SUCCESS_CODE
|         except IOError, e:
|             if fp:
|                 fp.close()
|             os.remove("bar.txt")
|             return ERROR_CODE

This is why in this case it is better to use goto's:
 
         fp = fopen("foo.txt", "w");
         if (fp == NULL)
	     goto out;

         for (i=0; i<10; i++)
             if (fprintf(fp, "%d\n", i) < 0)
		 goto out;

         if (fclose(fp) != 0)
	     got out;

         return SUCCESS_CODE;
out:
	 if (fp)
	     (void)fclose(fp);
	 remove("foo.txt");
	 return ERROR_CODE;

christos



More information about the bind10-dev mailing list