Fix potential memory leaks when encountering errors.