Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Обработка исключений с помощью блока try-catch

Блок try-catch предназначен для перехвата и обработки исключений, происходящих в исполняемом коде. Некоторые исключения могут обрабатываться в блоке catch, и проблема решается без повторного создания исключения. Но в большинстве случаев на этом этапе можно только проверить, что сгенерировано соответствующее исключение.

Пример

В этом примере IndexOutOfRangeException не является наиболее подходящим исключением. Для данного метода больше подходит исключение ArgumentOutOfRangeException, поскольку ошибка вызвана переданным методу параметром index.

-----

Примечания

Код, вызывающий исключение, находится в блоке try. Инструкция catch помещается сразу после него, чтобы обрабатывать исключение IndexOutOfRangeException, если оно происходит. В блоке catch исключение IndexOutOfRangeException обрабатывается, и вместо него создается более подходящее исключение ArgumentOutOfRangeException. Чтобы вызывающий объект получил максимально подробную информацию, рекомендуется указать исходное исключение в качестве значения InnerException нового исключения. Поскольку свойство InnerException доступно только для чтения, его значение необходимо присваивать только в конструкторе нового исключения.

How to: Execute Cleanup Code Using finally

The purpose of a finally statement is to ensure that the necessary cleanup of objects, usually objects that are holding external resources, occurs immediately, even if an exception is thrown. One example of such cleanup is calling Close on a FileStream immediately after use instead of waiting for the object to be garbage collected by the common language runtime, as follows:

static void CodeWithoutCleanup()

{

System.IO.FileStream file = null;

System.IO.FileInfo fileInfo = new System.IO.FileInfo("C:\\file.txt");

file = fileInfo.OpenWrite();

file.WriteByte(0xF);

file.Close();

}

Выполнение кода очистки с использованием блока finally

Инструкция finally предназначена для обеспечения немедленного выполнения необходимой очистки объектов, обычно занимающих внешние ресурсы, даже в случае, когда генерируется исключение. Примером подобной очистки является вызов метода Close для объекта класса FileStream сразу после его использования, не дожидаясь, когда этот объект будет уничтожен сборщиком мусора среды CLR, как показано ниже:

static void CodeWithoutCleanup()

{

System.IO.FileStream file = null;

System.IO.FileInfo fileInfo = new System.IO.FileInfo("C:\\file.txt");

file = fileInfo.OpenWrite();

file.WriteByte(0xF);

file.Close();

}

Example

To turn the previous code into a try-catch-finally statement, the cleanup code is separated from the working code, as follows.

static void CodeWithCleanup()

{

System.IO.FileStream file = null;

System.IO.FileInfo fileInfo = null;

try

{

fileInfo = new System.IO.FileInfo("C:\\file.txt");

file = fileInfo.OpenWrite();

file.WriteByte(0xF);

}

catch(System.UnauthorizedAccessException e)

{

System.Console.WriteLine(e.Message);

}

finally

{

if (file != null)

{

file.Close();

}

}

}

Because an exception can occur at any time within the try block before the OpenWrite() call, or the OpenWrite() call itself could fail, we are not guaranteed that the file is open when we try to close it. The finally block adds a check to make sure that the FileStream object is not null before you call the Close method. Without the null check, the finally block could throw its own NullReferenceException, but throwing exceptions in finally blocks should be avoided if it is possible.

A database connection is another good candidate for being closed in a finally block. Because the number of connections allowed to a database server is sometimes limited, you should close database connections as quickly as possible. If an exception is thrown before you can close your connection, this is another case where using the finally block is better than waiting for garbage collection.

Пример

Чтобы превратить предыдущий код в инструкцию try-catch-finally, код очистки отделяется от рабочего кода, как показано ниже.

------

Так как исключение может произойти в любой момент внутри блока try до вызова метода OpenWrite() или ошибкой может завершиться выполнение самого метода OpenWrite(), при выполнении попытки закрыть файл нет гарантии, что он открыт. Блок finally добавляет проверку, чтобы убедиться, что объект класса FileStream не имеет значения null, прежде чем вызывать метод Close. При отсутствии проверки значения null блок finally может сам генерировать исключение NullReferenceException, но генерирования исключений в блоках finally по возможности следует избегать.

Подключение к базе данных является еще одним кандидатом на закрывание в блоке finally. Так как допустимое число подключений к серверу базы данных иногда ограничено, их следует закрывать как можно быстрее. Если исключение генерируется прежде, чем можно закрыть подключение, то это еще один случай, когда лучше применить блок finally, чем ждать выполнения сборки мусора.

Interoperability

Interoperability enables you to preserve and take advantage of existing investments in unmanaged code. Code running under the control of the common language runtime (CLR) is called "managed code", and code that runs outside the CLR is "unmanaged code". COM, COM+, C++ components, ActiveX components, and Win32 API are examples of unmanaged code.

The .NET Framework enables interoperability with unmanaged code through platform invoke services, the System.Runtime.InteropServices namespace, and the CLR and through COM Interoperability (COM interop).

How to: Use Platform Invoke to Play a Wave File

The following C# code example illustrates how to use platform invoke services to play a wave sound file on the Windows operating system.

Example

This example code uses DllImport to import winmm.dll's PlaySound method entry point as Form1 PlaySound(). The example has a simple Windows Form with a button. Clicking the button opens a standard windows OpenFileDialog dialog box so that you can open a file to play. When a wave file is selected, it is played by using the PlaySound() method of the winmm.DLL assembly method. For more information about winmm.dll's PlaySound method, see Using PlaySound to Play Waveform-Audio Files. Browse and select a file that has a .wav extension, and then click Open to play the wave file by using platform invoke. A text box shows the full path of the file selected.

The Open Files dialog box is filtered to show only files that have a .wav extension through the filter settings:

dialog1.Filter = "Wav Files (*.wav)|*.wav";