Refactoring to remove try / catch

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.

+4
source share
6 answers

Try

 int nextColor; input = Console.ReadLine(); while( ! Int32.TryParse( input, out nextColor ) || nextColor > numColors || nextColor < 0 ) { Console.WriteLine("Unrecognized input: " + input); Console.WriteLine("Please enter a value between 0 and " + numColors + "."); input = Console.ReadLine(); } 
+14
source

warning, not verified!

 public int ChooseNextColor(int numColors) { while (true) { Console.Write("Please enter your next color selection: "); string input = Console.ReadLine(); int color; if (!int.TryParse(input, out color) || color > numColors || color < 0) { Console.WriteLine("Unrecognized input: " + input); Console.WriteLine("Please enter a value between 0 and " + numColors + "."); } else { return color; } } } 
+4
source

.NET provides TryParse only for this reason.

+2
source

You can use Int32.TryParse() or

 if (nextColor > numColors || nextColor < 0) { Console.WriteLine("Unrecognized input: " + input); Console.WriteLine("Please enter a value between 0 and " + numColors + "."); return null; } 
+1
source

If you want to avoid an exception, you should use the int.TryParse method instead of Convert.ToInt32 ().

+1
source
  public Int32 ChooseNextColor(Int32 numColors) { var success = false; while (!success) { Console.Write("Please enter your next color selection: "); int nextColor; var input = Console.ReadLine(); success = int.TryParse(input, out nextColor); if (success && nextColor > 0 && nextColor < numColors) return nextColor; Console.WriteLine("Unrecognized input: " + input); Console.WriteLine("Please enter a value between 0 and " + numColors + "."); } throw new ApplicationException("The thing that should not be."); } 
+1
source

All Articles