Книга: Fedora™ Unleashed, 2008 edition

Adding Some Error Checking

Adding Some Error Checking

Right now your program crashes in a nasty way if users don't provide at least two parameters. The reason for this is that we use arg[0] and arg[1] (the first and second parameters passed to your program) without even checking whether any parameters were passed in. This is easily solved: args is an array, and arrays can reveal their size. If the size doesn't match what you expect, you can bail out.

Add this code at the start of the Main() method:

if (args.Length != 2) {
 Console.WriteLine("You must provide exactly two parameters!");
 return;
}

The new piece of code in there is return, which is a C# keyword that forces it to exit the current method. As Main() is the only method being called, this has the effect of terminating the program because the user didn't supply two parameters.

Using the Length property of args, it is now possible for you to write your own Main() method that does different things, depending on how many parameters are provided. To do this properly, you need to use the else statement and nest multiple if statements like this:

if (args.Length == 2) {
 /// whatever...
} else if (args.Length == 3) {
 /// something else
} else if (args.Length == 4) {
 /// even more
} else {
 /// only executed if none of the others are
}

Оглавление книги


Генерация: 1.323. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз