Set exit code and handle cleanup on exceptions.