Code for db query finished but throws exception