Add scoped function

Add a function to handle the common enter-leave pattern.
The finally block is executed after the return statement.