user2883073
user2883073

Reputation:

Exceptions (try & catch?)

I want to restrict values to the variable anzahlMinen to numbers from 0 to 24.

How do I do that? I know exceptions, but I failed doing it.

static void Main(string[] args)
    {
      Console.WindowHeight = 23;
      Console.WriteLine("Mit wievielen Bomben möchten Sie spielen?");
      int anzahlMinen = int.Parse(Console.ReadLine());

Upvotes: 1

Views: 85

Answers (2)

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

you can use TryParse, to handle non-numeric values and parse it to int, then check if number is between 0 and 24 and handle wrong numbers in if

int i=0;

var isNumber = int.TryParse(eingabe,out i);

if(!isNumber || (i<0 || i>24))
{
   Console.WriteLine("Wrong Number");
   //break or whatever
   //possibly use continue; to go back to first line of while
   continue;
}

do not throw exception here, because if you can handle exceptional case without throwing and catching, you shouldn't use try/catch. Try catch is an expensive mechanism and in such simple cases is an overkill.

Upvotes: 1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

You don't need exceptions for what you want to do:

string eingabe = Console.ReadLine();
int anzahlMinen = 0;
if (!Int32.TryParse(eingabe, out anzahlMinen))
    Console.WriteLine("Dies ist keine gültige Zahl!");
else if (anzahlMinen < 0 || anzahlMinen > 24)
    Console.WriteLine("Anzahl Minen muss zwischen 0 und 24 liegen!");

Why you don't need/shoud not use exceptions here:

Exceptions are used to indicate an unexpected state or error in the program flow. The user entering a non-number or an invalid value is not unexpected and should be handled.

Also, creating and catching exceptions has a huge impact on the performance of your application, so you should avoid throwing exceptions unnecessarily.

Thirdly, exceptions indicate errors and should never ever be used as a means to control program flow!

Upvotes: 3

Related Questions