Added exception handling in calculate_stats