More error handling using exceptions and some code optimization.