A lot of suspicious and shaky coding, but try..catch should work.  Needs cleanup and more tests.