The loop accepts user input into the string and parses it, in case of unsuccessful parsing or request to the server via ScreenName - returns an Exception. What condition can be put to the cycle so that it repeats until the user enters the correct value and the method does not return the correct answer?

int? numberId; while (true) { Console.WriteLine("Введите Id, либо ScreenName группы"); var enterId = Console.ReadLine(); numberId = taskLogic.IdTreatment(enterId); if(numberId != null) break; } public int? IdTreatment(string enterId) { if (int.TryParse(enterId, out int numberId)) { Console.WriteLine("Id принят успешно"); return (int?)numberId; } else { Console.WriteLine("Обнаружен ScreenName"); numberId = (int)api.Utils.ResolveScreenName(enterId).Id.Value; return (int?)numberId; } } 
  • And what is your if(numberId == null) does not suit you? If you need to handle Exception, then try-catch with a null return. This is a very bad practice, no need to build the logic of the program on exceptions. But if you don’t have a choice, why is this option not suitable for you? - Lunar Whisper
  • Not suitable because it does not work). So I’m putting the loop in try \ catch for processing so that the program does not crash - but returns an error for understanding. However, the program just goes into catch and wants to close after, not returning to the cycle - Timur Alekseev
  • @LunarWhisper something like that - Timur Alekseev
  • So, probably, this is because your loop is wrapped in try-catch and you need try-catch inside a loop? ;) - Lunar Whisper

1 answer 1

But again, this is a very bad practice - to build business logic based on exceptions.

 int? numberId; while (true) { Console.WriteLine("Введите Id, либо ScreenName группы"); var enterId = Console.ReadLine(); numberId = taskLogic.IdTreatment(enterId); if(numberId != null) break; } public int? IdTreatment(string enterId) { if (int.TryParse(enterId, out int numberId)) { Console.WriteLine("Id принят успешно"); return (int?)numberId; } else { try { Console.WriteLine("Обнаружен ScreenName"); numberId = (int)api.Utils.ResolveScreenName(enterId).Id.Value; return (int?)numberId; } catch (Exception) { return null; } } } 
  • Thanks for the answer!. For the sake of development - how would you in theory implement this re-entry? - Timur Alekseev