Fixed potential issues to release resources when error occurs.