Improved error handling and termination