Properly release lock on error conditions