15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

356 ❘ ChaPTer 15 errOrs And exceptiOns<br />

The program then continues to ask for more numbers for processing until the user simply presses the Enter<br />

key without entering anything.<br />

You should note that this code does not provide a good example of when to use<br />

exception h<strong>and</strong>ling. As already indicated, the idea of exceptions is that they are<br />

provided for exceptional circumstances. Users are always typing in silly things, so this<br />

situation doesn’t really count. Normally, your program will h<strong>and</strong>le incorrect user input<br />

by performing an instant check <strong>and</strong> asking the user to retype the input if there is a<br />

problem. However, generating exceptional situations is diffi cult in a small example that<br />

you can read through in a few minutes! So, we will tolerate this bad practice for now<br />

to demonstrate how exceptions work. The examples that follow present more realistic<br />

situations.<br />

The code for SimpleExceptions looks like this:<br />

using System;<br />

namespace Wrox.ProCSharp.AdvancedCSharp<br />

{<br />

public class MainEntryPoint<br />

{<br />

public static void Main()<br />

{<br />

while (true)<br />

{<br />

try<br />

{<br />

string userInput;<br />

Console.Write("Input a number between 0 <strong>and</strong> 5 " +<br />

"(or just hit return to exit) > ");<br />

userInput = Console.ReadLine();<br />

if (userInput == "")<br />

{<br />

break;<br />

}<br />

int index = Convert.ToInt32(userInput);<br />

if (index < 0 || index > 5)<br />

{<br />

throw new IndexOutOfRangeException(<br />

"You typed in " + userInput);<br />

}<br />

Console.WriteLine("Your number was " + index);<br />

}<br />

catch (IndexOutOfRangeException ex)<br />

{<br />

Console.WriteLine("Exception: " +<br />

"Number should be between 0 <strong>and</strong> 5. {0}", ex.Message);<br />

}<br />

catch (Exception ex)<br />

{<br />

Console.WriteLine(<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!