Factoring error/termination handler out thanks to suggestion from fschaefer