Is there a way to run an expression on.exit() but only if completes normally, not on error?

后端 未结 3 1303
情深已故
情深已故 2021-01-08 00:48

I\'m aware of the function on.exit in R, which is great. It runs the expression when the calling function exits, either normally or as the result of an error.

3条回答
  •  失恋的感觉
    2021-01-08 01:28

    Just wrap the args of all your return function calls with the code that you want done. So your example becomes:

    foo = function(thing){do something; return(thing)}
    myfunction = function() {
         ...
         if (...) then return( foo(point 1) )
         ...
         if (...) then return( foo(point 2) )
         ...
         if (...) then return( foo(point 3) )
         ...
         return ( foo(point 4) )
    }
    

    Or just make each then clause into two statements. Using on.exit to lever some code into a number of places is going to cause spooky action-at-a-distance problems and make the baby Dijkstra cry (read Dijkstra's "GOTO considered harmful" paper).

提交回复
热议问题