Moved exception handling around and made a few things more generic.