move error handling code to top