Clean up I/O

This pull request improves exception handling in the IO routines, moving as much code as possible out of the try/except blocks.