Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Visual CSharp 2005 Express Edition (2006) [eng]

.pdf
Скачиваний:
42
Добавлен:
16.08.2013
Размер:
9.96 Mб
Скачать

Chapter 7

Figure 7-8

As you can see in Figure 7-8 there isn’t much difference when using the two statements with an expression that is true more than the first time through the loop. However, when you use an expression that evaluates to false the first time, you can see the difference.

8.Type 6; then click the button added in Step 1. Since 6 comes back false the first time (intCurr < 5), then the while statement never gets executed. You can see this in Figure 7-9.

Figure 7-9

Hopefully you can see the difference between the two. As with selection-type statements, you will gain confidence and see where you will use one type of iteration statement over the other.

114

Selections, Iterations, and Catching Exceptions

Catching Exceptions in Your Code

When you are writing code you will have errors that occur at runtime. Even if you write the most perfect code in the world, there will be issues that happen because of outside influences. An important feature of the code is to be able to handle the errors when they do occur, and keep the application running. As mentioned, these errors in .NET are called exceptions. Exceptions can occur for a variety of reasons, and in fact there are even classes created in .NET to help you trap and handle the exceptions.

If left unhandled, your application will give a rude error message and dump you out to Windows. If running in the Release mode into the code if in Debug, which is the default mode for running. Before seeing how to trap the exceptions mentioned in the last paragraph, I want you to see what it looks like to have an exception to occur unhandled.

Try It Out

Create a Routine with an Unhandled Exception

Using the form you created for the chapter:

1.Drag and drop another Button control onto the form.

2.Name it as desired. For this example the Button control was named btnUnhandledException.

3.Double-click the btnUnhandledException button. The btnUnhandledException_Click routine is created as shown here:

private void btnUnhandledException_Click(object sender, EventArgs e)

{

}

4.Type the following lines of code:

int intCurr = Convert.ToInt32(this.textBox1.Text); textBox2.Text = Convert.ToString(intCurr + 3);

This code can break if a nonnumeric value is entered in textBox1. This includes no value. You can see the complete routine here:

private void btnUnhandledException_Click(object sender, EventArgs e)

{

int intCurr = Convert.ToInt32(this.textBox1.Text); textBox2.Text = Convert.ToString(intCurr + 3);

}

5.Press F5 to build and execute the application.

6.Click the new button you added in Step 1 without putting any value in textBox1. The error is displayed in Figure 7-10.

While the rest of the chapter discusses the various ways to catch exceptions, I generally let the exceptions occur while I am writing the code, until I am ready to release it. The reason is that you can see some of the exceptions that can occur and possibly program for them.

115

Chapter 7

Figure 7-10

Starting Off Easy with try...catch Statements

To catch exceptions you will start with the try . . . catch statements, the syntax of which can be seen here:

try

{

}

Catch[(exceptiontype variable)]

{

}

For now, don’t worry about the (exceptiontype variable) portion of the syntax. When you just want to catch and handle any exception that occurs, you can use the try . . . catch statements alone. As an example, taking the two lines of code from the last section, you can wrap the code with the try code block and then handle resulting exceptions with the catch code block. Here is how it looks:

try

{

int intCurr = Convert.ToInt32(this.textBox1.Text);

116

Selections, Iterations, and Catching Exceptions

textBox2.Text = Convert.ToString(intCurr + 3);

}

catch

{

textBox2.Text = “Exception Occurred”;

}

In this code a literal string is placed into the Textproperty of textBox2 to let the user know an error has occurred. Sometimes that is the way you handle exceptions, by simple displaying a message that informs the user that an exception has occurred.

Try It Out

Use the try...catch statements

Using the form you created for the chapter:

1.Drag and drop another Button control onto the form.

2.Name it as desired. For this example the Button control was named btnTryCatch.

3.Double-click the btnTryCatch button. The btnTryCatch_Click routine is created as shown here:

private void btnTryCatch_Click(object sender, EventArgs e)

{

}

4.Type the following lines of code:

try

{

int intCurr = Convert.ToInt32(this.textBox1.Text); textBox2.Text = Convert.ToString(intCurr + 3);

}

catch

{

textBox2.Text = “Exception Occurred”;

}

This code can break if a nonnumeric value is entered in textBox1. This includes no value. You can see the complete routine here:

private void btnTryCatch_Click(object sender, EventArgs e)

{

try

{

int intCurr = Convert.ToInt32(this.textBox1.Text); textBox2.Text = Convert.ToString(intCurr + 3);

}

catch

{

textBox2.Text = “Exception Occurred”;

}

}

117

Chapter 7

5.Press F5 to build and execute the application.

6.Click the new button you added in Step 1. Because you did not add any value in textBox1, the error occurs and the line of code in the catch statement is displayed, as shown in Figure 7-11.

Figure 7-11

Using the finally Statement

Sometimes you want to have certain lines of code to execute regardless of whether the code caused an exception or not. The syntax for this will look as follows:

try

{

}

catch

{

}

finally

{

}

The finally block will occur whether the try block throws an exception or not. The finally block

is a great place to put any cleanup code that you want to have run. Here is the code used for the current example:

private void btnTryCatchFinally_Click(object sender, EventArgs e)

{

try

{

int intCurr = Convert.ToInt32(this.textBox1.Text);

118

Selections, Iterations, and Catching Exceptions

textBox2.Text = Convert.ToString(intCurr + 3);

}

catch

{

textBox2.Text = “Exception Occurred”;

}

finally

{

textBox2.Text += Environment.NewLine + “Completed”;

}

}

In this example the same two lines of code are run to cause the exception to occur. The catch statement stores the string literal into textBox2. Lastly, the finally statement code block adds a NewLine statement and adds it to a string literal “Completed”. So regardless of what you put in the TextBox, this code will place the word “Completed” after the value in the TextBox.

Try It Out

Use the try...catch...finally Statements

Using the form you created for the chapter:

1.Drag and drop another Button control onto the form.

2.Name it as desired. For this example the Button control was named btnTryCatchFinally.

3.Double-click the btnTryCatchFinally button. The btnTryCatchFinally_Click routine is created as shown here:

private void btnTryCatchFinally_Click(object sender, EventArgs e)

{

}

4.Type the following lines of code:

try

{

int intCurr = Convert.ToInt32(this.textBox1.Text); textBox2.Text = Convert.ToString(intCurr + 3);

}

catch

{

textBox2.Text = “Exception Occurred”;

}

finally

{

textBox2.Text += Environment.NewLine + “Completed”;

}

The final block of code looks like this:

119

Chapter 7

private void btnTryCatchFinally_Click(object sender, EventArgs e)

{

try

{

int intCurr = Convert.ToInt32(this.textBox1.Text); textBox2.Text = Convert.ToString(intCurr + 3);

}

catch

{

textBox2.Text = “Exception Occurred”;

}

finally

{

textBox2.Text += Environment.NewLine + “Completed”;

}

}

5.Press F5 to build and execute the application.

6.Type 1 in the first text box.

7.Click the new button you added in Step 1. Since a legitimate entry was made in textBox1, no error occurs, and the “Completed” message is displayed (see Figure 7-12).

Figure 7-12

8.Now delete the entry in textBox1.

9.Click the new button you added in Step 1. Now you will see the message that an exception occurred, and also still see the “Completed” message provided by the finally statement (see Figure 7-13).

There is definitely more you can do to the try . . . catch code blocks, especially when you add in code to track specific errors.

120

Selections, Iterations, and Catching Exceptions

Figure 7-13

Summar y

If all you could do in a programming language is just write single lines of code that execute one by one without making any decisions or selecting blocks of code on those decisions, you may not be able to accomplish some tasks. Either that or it would either take a lot more code to accomplish it. The same could be especially said when you have the occasion to make iterations such as working through the days of the month. You would need to write the same piece of code, maybe changing one or two lines, for each day of the month. At the risk of sounding technical, it would be a pain, to say the least.

C# provides statements such as if . . . else and switch . . . case for selecting code, and for statements as well as others to help with iterating through code. Which of the statements just mentioned you use will depend on what task you are trying to handle in the code. This chapter discussed how to use these statements. It also discussed how to trap errors, called exceptions, that can occur at runtime. Lastly, the chapter talked about what you can do with the exceptions that occur.

Exercises

1.When would you use an if . . . else statement versus a switch . . . case statement?

2.What category of statements does the if . . . else statement fall into?

3.What is the different between the for and foreach statements?

4.Which statement, do or while, does the code execute at least one code block if the expression starts as false?

5.If the developer wants to have a code block occur whether an exception occurs or not, which statement does the developer use with the try statement?

121

Part II

Creating Applications

with C# Express

Соседние файлы в предмете Программирование на C++