Any ideas on a good way to refactor this so that my code acts the same, but without any throwing and detecting my own exception?
public Int32 ChooseNextColor(Int32 numColors) { int? nextColor = null; while (nextColor == null) { Console.Write("Please enter your next color selection: "); string input = Console.ReadLine(); try { nextColor = Convert.ToInt32(input); if (nextColor > numColors || nextColor < 0) throw new ArgumentOutOfRangeException(); } catch { nextColor = null; Console.WriteLine("Unrecognized input: " + input); Console.WriteLine("Please enter a value between 0 and " + numColors + "."); } } return (nextColor.Value); }
EDIT : The try / parse method is exactly what I'm looking for.
In response to editing the John header โ I should have posted more info to get started, and it would be โbetter to get rid of try / catch all togetherโ. Therefore, bearing in mind, I changed the name.
source share