Refactor locking and exception code

Use C++ Templates and Lambdas to keep locking code in one place.