www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - suggestion: finally for return values

reply Dan <ddaglas gmail.com> writes:
How about modifying D to accept a finally clause for use with function/method
return values.  For example:

int foo(int a, double b) {
  try {
    ...
    return num;
    ...
  } catch (Exception exc) {
    ...
  } finally {
    ...{statements A}...
  } finally(int retval) {
    ...{statements B}...
  }
}

statements B will execute when the try block executes "return num;", passing
num into the finally clause as "retval".  Whether statements A also executes
in this case is up for discussion.

--Dan
Dec 09 2006
next sibling parent "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Dan" <ddaglas gmail.com> wrote in message 
news:elf8vj$rqs$1 digitaldaemon.com...
 How about modifying D to accept a finally clause for use with 
 function/method
 return values.  For example:

 int foo(int a, double b) {
  try {
    ...
    return num;
    ...
  } catch (Exception exc) {
    ...
  } finally {
    ...{statements A}...
  } finally(int retval) {
    ...{statements B}...
  }
 }

 statements B will execute when the try block executes "return num;", 
 passing
 num into the finally clause as "retval".  Whether statements A also 
 executes
 in this case is up for discussion.
You can do this with 'out' i.e. int foo(int a, double b) out(result) { ...statements B... } body { try { ...return num; } finally { ...statements A... } } But being a contract, it'll only be compiled in non-release mode. :| I supposed one workaround would be to just put the result into a local variable before returning it, so you can access it in the finally block.
Dec 09 2006
prev sibling parent Stewart Gordon <smjg_1998 yahoo.com> writes:
Dan wrote:
 How about modifying D to accept a finally clause for use with function/method
 return values.  For example:
 
 int foo(int a, double b) {
   try {
     ...
     return num;
     ...
   } catch (Exception exc) {
     ...
   } finally {
     ...{statements A}...
   } finally(int retval) {
     ...{statements B}...
   }
 }
 
 statements B will execute when the try block executes "return num;", passing
 num into the finally clause as "retval".  Whether statements A also executes
 in this case is up for discussion.
What _would_ statements A be for then? Simply to return something if an exception kicks in before the return statement? I'm not sure about this. Moreover, the TryStatement syntax already suffers from a version of the dangling else problem. Supporting multiple finally clauses might complicate the matter more (not to mention break some existing code). Stewart.
Dec 10 2006