Exception handling, better memory release.

Memory release tested.