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.>
Bit more readable version of my comment on @Joris' answer:
f = function() {
ret = local({
myvar = 42
if (runif(1) < 0.5)
return(2)
stop('oh noes')
}, environment())
# code to run on success...
print(sprintf('myvar is %d', myvar))
ret
}