Improved exception handling and fixed test