Avoid possible memory leaks in case of exceptions

Change-Id: Ic88b22895c2eb4144d31f22a0f7bc98971873262