Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# ПІДРУЧНИКИ / c# / Manning - Windows.forms.programming.with.c#.pdf
Скачиваний:
108
Добавлен:
12.02.2016
Размер:
14.98 Mб
Скачать
InitializeCompo-

Figure 2.5

The Visual Studio Options dialog box can be used to enable or disable the statement completion feature.

Back to our btnLoad_Click method, the code used here matches the code used for the MyForm program in chapter 1. Take another look at the

nent method in the Windows Form Designer generated code region. You will notice that Visual Studio has added the Click event handler for the btnLoad control.

this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click);

Compile and run the application to verify that the program can now load and display an image. Try loading different images into the program.

If you recall, we noted in chapter 1 that this code presumes the selected file can be turned into a Bitmap object. If you select a nonimage file, the program exits in a most unfriendly manner. This is a fine opportunity to fix this problem, so we’ll make it the subject of our next section.

2.3.2Exception handling

You may well be familiar with exception handling, since a number of C++ development environments, including earlier Microsoft environments, support this feature. Newer languages such as Java also support exceptions. Exception handling came into existence as a common way to deal with errors in a program. In our application, we expect the user to select a JPEG or other image file that can be opened as a Bitmap object. Most of the time, no error occurs. However, if a corrupted or invalid JPEG file is selected, or if the operating system is low on memory, then this creates an exceptional condition where it may not be possible to create our Bitmap. Since such situations will certainly occur, a way to recognize such errors is required.

Since some C++ programmers may not be familiar with exception handling, we will look at some alternative approaches before discussing exceptions in .NET. As one approach, we could use static creation methods that include an error field. For example, our code might look like the following:

58

CHAPTER 2 GETTING STARTED WITH VISUAL STUDIO .NET

// Wrong way #1 to support error handling int err = 0;

Bitmap bm = Bitmap.CreateObject(dlg.OpenFile(), err); if (err != 0) {

// An error occurred

if (err == bad_file_error) {

// Indicate to the user that the file could not be loaded.

}

else if (err == memory_error) {

// Indicate that memory is running low.

}

return;

// on error abort the event handler

}

// Assign the newly created Bitmap to our PictureBox pbxPhoto.Image = bm;

This code would certainly work, but it requires extra variables and the programmer must check for errors every time a bitmap is created. This might be problematic if the programmer forgets or a new error is added which is not handled by the code. Then our design is for naught and bad things will happen. In critical production code, the mishandling of errors can lead to serious problems such as corrupted database information, unexpected stock trades, or other actions that a user or a program would not normally allow to happen. So this solution does not provide the best guarantees for program and data stability.

A second way to handle errors is to provide a global GetLastError function. This solution was used by Microsoft prior to the MFC environment, and is still used in some cases within MFC. It looks something like this:

// Wrong way #2 to support error handler Bitmap bm = new Bitmap(dlg.OpenFile()); int err = GetLastError();

if (err != 0) {

// Handle error values much like the above code

}

This is more elegant than the previous method, but has all the same problems. Programmers may forget to use it, and error codes change from release to release.

Exceptions provide a solution to these problems by forcing a programmer to deal with them, and provide guarantees that the program will exit if they do not. When an exception is not caught by a program, the program will exit. A forced exit is much safer than continuing to run in an error state and risk compromising critical data.

More formally, an exception is an unexpected error, or exceptional condition, that may occur in a program. Code that creates such a condition is said to throw the exception, and code that processes the condition is said to catch the exception. In .NET,

LOADING FILES

59

Sys-

exceptions are implemented as classes. Almost all exceptions inherit from the tem.Exception class.

One problem with exceptions in other languages is that they are expensive to support. Modern languages like Java and C# have done away with this problem by designing exceptions into the language so that compilers can handle them cheaply and gracefully.

The format used to process exceptions is the well-known try-catch blocks used in distributed computing interfaces and C++ development environments for many years. A portion of code where exceptions may be caught is enclosed in a try block, and the portion of code that handles an exception is enclosed in a catch block. We will discuss this syntax in more detail in a moment. First, let’s add such a block to the code where we create the Bitmap object. Here is our existing code:

if (dlg.ShowDialog() == DialogResult.OK)

{

imgPhoto.Image = new Bitmap(dlg.OpenFile());

}

The following table details how to catch exceptions in this code.

CATCH EXCEPTIONS IN THE BTNLOAD_CLICK METHOD

 

Action

Result

 

 

 

1

Edit the MainForm.cs source

Note: You can search this file by hand, or use the drop-

 

file and locate the

down box in the top portion of the source code window

 

btnLoad_Click method.

to select this method explicitly.

 

 

 

2

Insert a try block around the

The changes to the existing code are shown in bold.

 

Bitmap creation code.

if (dlg.ShowDialog() == DialogResult.OK)

 

 

 

 

{

 

 

try

 

 

{

 

 

imgPhoto.Image = new Bitmap(dlg.OpenFile());

 

 

}

 

 

}

 

 

 

3

Add a catch block to catch

if (dlg.ShowDialog() == DialogResult.OK)

 

any exceptions that may

{

 

occur in the try block.

try

 

{

 

 

 

 

imgPhoto.Image = new Bitmap(dlg.OpenFile());

 

 

}

 

 

catch (Exception ex)

 

 

{

 

 

// Handle exception

 

 

}

 

 

}

 

 

Note: Event handlers in Visual Studio .NET tend to use

 

 

an “e” parameter for the event parameter to the call. To

 

 

ensure we avoid a conflict, we will use ex as a standard

 

 

variable name for an Exception object.

 

 

 

60

CHAPTER 2 GETTING STARTED WITH VISUAL STUDIO .NET

Соседние файлы в папке c#