Improve error checking

Print more useful error messages, if unexpected errors occur.