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 ❘ 217<br />

program, which is available for download on this book’s website, uses the following code to install<br />

its event handler.<br />

// Install the global exception handler.<br />

private void Form1_Load(object sender, EventArgs e)<br />

{<br />

Application.ThreadException += ThreadException;<br />

}<br />

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

// Handle global exceptions.<br />

private static void ThreadException(object sender, ThreadExceptionEventArgs e)<br />

{<br />

try<br />

{<br />

string message = e.Exception.Message + '\n' +<br />

"Do you want to try to continue";<br />

if (MessageBox.Show(message, "Unhandled Exception",<br />

MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.No)<br />

{<br />

Application.Exit();<br />

}<br />

}<br />

catch<br />

{<br />

Application.Exit();<br />

}<br />

}<br />

The event handler does all its work inside a try catch block. If anything goes wrong, the code simply<br />

closes the application.<br />

The code builds and displays a message that describes the exception and asks the user if the program<br />

should try to continue. (You might also want to log the error, including a stack trace, into a log file<br />

or a system log.) If the user clicks No, the method calls Application.Exit to end the program.<br />

If the user clicks Yes, the program continues running.<br />

When you click the program’s Throw Exception button, the following code executes.<br />

// Throw an exception.<br />

private void throwExceptionButton_Click(object sender, EventArgs e)<br />

{<br />

throw new ArgumentException();<br />

}<br />

This code simply throws an ArgumentException. Because this code doesn’t use a try catch block,<br />

the global exception handler catches it.<br />

WPF Applications<br />

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

.Current object’s DispatcherUnhandledException event. The WpfGlobalException example<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!