Added error handling to cost calculation.