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

Create successful ePaper yourself

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

222 ❘ CHAPTER 9 Error Handling<br />

described in the previous sections, if one exists. If there is no UnhandledException event handler, the<br />

program crashes.<br />

If you include a catch statement with no exception type, that block matches any exception. If<br />

the raised exception doesn’t match any of the previous exception types, the program executes the<br />

finalExceptionStatements block of code. Note that the statement catch (Exception ex) also<br />

matches all exceptions, so it’s just as good as catch by itself. It also gives you easy access to the<br />

exception object’s properties and methods.<br />

You can figure out what exception classes to use in catch statements in several ways. First, you can<br />

spend a lot of time digging through the online help. An easier method is to let the program crash<br />

and then look at the error message it produces.<br />

Figure 9-4 shows the error message a program throws when it tries to use the Integer.Parse<br />

method to convert the non-numeric string Hello into an integer. The first line in the dialog makes<br />

it obvious that the program should catch FormatException.<br />

Figure 9-4: When a program crashes, the message it<br />

generates tells you the type of exception it threw.<br />

Another way to decide what types of exceptions to catch is to place a final generic catch (Exception<br />

ex) statement at the end of the catch list. Place code inside that catch block to display the exception’s<br />

type name, as shown in the following code.<br />

try<br />

{<br />

...<br />

}<br />

... Catch blocks ...<br />

catch (Exception ex)<br />

{<br />

MessageBox.Show("Unexpected exception " + ex.GetType().Name);<br />

}<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!