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.

Chapter 10 ❘ 655<br />

The button’s event handler does all its work inside a try-catch block. The first two catch<br />

sections display messages that the user can understand. The third catch section handles unexpected<br />

exceptions. Because it doesn’t know what kinds of exceptions to expect, it can’t display<br />

a user-friendly message. Instead it just writes the exception’s name into the Console window<br />

(so you can add a catch section for it) and displays the exception’s message to the user.<br />

The Factorial function throws an ArgumentOutOfRangeException if its parameter<br />

is negative. It then uses a checked block to watch for arithmetic errors and calculates the<br />

factorial. (See the section “Casting Numbers” in Chapter 4, “Data Types, Variables, and<br />

Constants,” for a review of checked blocks.)<br />

Chapter 10<br />

1. The TraceFactorial example program, which is available in this book’s downloads,<br />

includes code for Exercises 1, 2, and 4. It uses the following code to solve Exercise 1.<br />

(Notice how the code needs to separate the recursive call from the return statement so<br />

that it can display the method’s result before returning.)<br />

private long Factorial(long number)<br />

{<br />

Debug.WriteLine("Factorial(" + number.ToString() + ")");<br />

Debug.Indent();<br />

long result;<br />

if (number

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

Saved successfully!

Ooh no, something went wrong!