Книга: 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
}
- 9.3 Error Frame
- 9.9.6 Error Recognition Mode
- Adding a New Catalog Item to an OS Design
- SCTP ERROR chunk
- 6.1 Adding on to Eclipse
- Adding New Users
- Checking for the Availability of the Loopback Interface
- When Something Goes Wrong
- Errors During Compile
- Runtime Errors, Boot Loader Problems, and Kernel Oops
- 3.3.4 Spellchecking on the Fly with Flyspell
- Checking Hardware Compatibility