improve exception handling and fix minor bugs