03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Bugs Versus Undesirable Conditions ❘ 219<br />

Console Applications<br />

To catch unhandled exceptions in a console application, add an event handler to the<br />

AppDomain.CurrentDomain object’s UnhandledException event. The Main method used by<br />

the ConsoleGlobalException example program, which is available for download on the book’s<br />

website, installs its event handler and enters a loop that runs until the program ends.<br />

static void Main(string[] args)<br />

{<br />

// Install the event handler.<br />

AppDomain.CurrentDomain.UnhandledException += UnhandledException;<br />

// Loop forever.<br />

for (; ; )<br />

{<br />

Console.WriteLine("1 - Continue, 2 - Throw exception, 3 - Exit");<br />

Console.Write("> ");<br />

string text = Console.ReadLine();<br />

int choice = int.Parse(text);<br />

switch (choice)<br />

{<br />

case 1:<br />

// Continue.<br />

Console.WriteLine("Continuing...\n");<br />

break;<br />

case 2:<br />

// Throw an exception.<br />

Console.WriteLine("Throwing exception...\n");<br />

throw new ArgumentException();<br />

}<br />

}<br />

}<br />

case 3:<br />

// Exit.<br />

return;<br />

The method installs the program’s event handler and then enters an infinite loop. Each time through<br />

the loop, the method displays a prompt and then waits for the user’s input. It parses the input and<br />

uses a switch statement to decide what to do next.<br />

If the user enters 1, the program displays a message and continues its loop. If the user enters 2, the<br />

program throws an exception. If the user enters 3, the program exits the Main method and ends.<br />

The following code shows the example program’s UnhandledException event handler.<br />

// Handle an exception.<br />

private static void UnhandledException(object sender,<br />

UnhandledExceptionEventArgs e)<br />

{<br />

Console.WriteLine("Caught exception:");<br />

Exception exception = (Exception)e.ExceptionObject;<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!