Use exception and correct memory leaks due to use of exit