If i read your question correct: You have list called
ID in which you have numeric ids (user and group ids) and you want to add the name of the user or group corresponding to the id to an other list (called lstUsers or lstGroups).
The exception is to be expected if the id being handled is the id of a group. The function
web.SiteUsers.GetById() throws an exception when the given id is not found and that is what you try first. Try wrapping it in a
Bonus: store SiteUsers and SiteGroups in a variable, to avoid getting this infomation over and over again from the database in each iteration of the loop.
SPUserCollection users = web.SiteUsers;
SPGroupCollection groups = web.SiteGroups;
foreach (var id in ID)
// try to get user-name
SPUser spUser = users.GetByID(Convert.ToInt32(id));
if (spUser != null)
// no user found with id.
// try to get group-name
SPGroup spGroup = groups.GetByID(Convert.ToInt32(id ));
if (spGroup != null)
// no group found with id
// If execution reaches this point: Nothing found with this id