made error handling more consistent and added exit function