Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

Chapter 6 Managing Errors and Exceptions

111

result.Text = fEx.Message;

}

This catch handler catches the FormatException thrown by int.Parse and then displays in the result text box at the bottom of the form the text in the exception’s Message

property.

12.On the Debug menu, click Start Without Debugging.

13.Type John in the left operand text box, and then click Calculate.

The catch handler successfully catches the FormatException, and the message “Input string was not in a correct format” is written to the Result text box. The application is now a bit more robust.

14.Replace John with the number 10, type Sharp in the right operand text box, and then click Calculate.

Notice that because the try block surrounds the statements that parse both text boxes, the same exception handler handles user input errors in both text boxes.

15.Click Quit to return to the Visual Studio 2008 programming environment.

Using Checked and Unchecked Integer Arithmetic

In Chapter 2, you learned how to use binary arithmetic operators such as + and * on primitive data types such as int and double. You also saw that the primitive data types have a fixed

size. For example, a C# int is 32 bits. Because int has a fixed size, you know exactly the range of value that it can hold: it is –2147483648 to 2147483647.

Tip If you want to refer to the minimum or maximum value of int in code, you can use the int. MinValue or int.MaxValue property.

112 Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008

The fixed size of the int type creates a problem. For example, what happens if you add 1 to an int whose value is currently 2147483647? The answer is that it depends on how the application is compiled. By default, the C# compiler generates code that allows the calculation to overflow silently. In other words, you get the wrong answer. (In fact, the calculation wraps around to the largest negative integer value, and the result generated is –2147483648.) The reason for this behavior is performance: integer arithmetic is a common operation in almost every program, and adding the overhead of overflow checking to each integer expression could lead to very poor performance. In many cases, the risk is acceptable because you know (or hope!) that your int values won’t reach their limits. If you don’t like this approach, you can turn on overflow checking.

Tip You can activate and disable overflow checking in Visual Studio 2008 by setting the project properties. On the Project menu, click YourProject Properties (where YourProject is the name of your project). In the project properties dialog box, click the Build tab. Click the Advanced button in the lower-right corner of the page. In the Advanced Build Settings dialog box, select or clear the Check for arithmetic overflow/underflow check box.

Regardless of how you compile an application, you can use the checked and unchecked keywords to turn on and off integer arithmetic overflow checking selectively in parts of an application that you think need it. These keywords override the compiler option specified for the project.

Writing Checked Statements

A checked statement is a block preceded by the checked keyword. All integer arithmetic in a checked statement always throws an OverflowException if an integer calculation in the block

overflows, as shown in this example:

int number = int.MaxValue; checked

{

int willThrow = number++; Console.WriteLine(“this won’t be reached”);

}

Important Only integer arithmetic directly inside the checked block is subject to overflow checking. For example, if one of the checked statements is a method call, checking does not apply to code that runs in the method that is called.

Chapter 6 Managing Errors and Exceptions

113

You can also use the unchecked keyword to create an unchecked block statement. All integer arithmetic in an unchecked block is not checked and never throws an OverflowException. For

example:

int number = int.MaxValue; unchecked

{

int wontThrow = number++; Console.WriteLine(“this will be reached”);

}

Writing Checked Expressions

You can also use the checked and unchecked keywords to control overflow checking on inte-

ger expressions by preceding just the individual parenthesized expression with the checked or unchecked keyword, as shown in this example:

int wontThrow = unchecked(int.MaxValue + 1); int willThrow = checked(int.MaxValue + 1);

The compound operators (such as += and -=) and the increment (++) and decrement (--) operators are arithmetic operators and can be controlled by using the checked and unchecked keywords. Remember, x += y; is the same as x = x + y;.

Important You cannot use the checked and unchecked keywords to control floating-point (noninteger) arithmetic. The checked and unchecked keywords apply only to integer arithmetic using data types such as int and long. Floating-point arithmetic never throws OverflowException—not

even when you divide by 0.0. (The .NET Framework has a representation for infinity.)

In the following exercise, you will see how to perform checked arithmetic when using Visual Studio 2008.

Use checked expressions

1.Return to Visual Studio 2008.

2.On the Debug menu, click Start Without Debugging. You will now attempt to multiply two large values.

3.Type 9876543 in the left operand text box, type 9876543 in the right operand text box, select the Multiplication option, and then click Calculate.

The value –1195595903 appears in the Result text box on the form. This is a negative

value, which cannot possibly be correct. This value is the result of a multiplication operation that silently overflowed the 32-bit limit of the int type.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]