Improved exception handling and logging