Added standard error handling with exception class

Also moved the setup code into its own function.