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

Обработка исключений

Блок try используется программистами на C# для разделения кода, который может находиться под влиянием исключения, а блоки catch используются для обработки итоговых исключений. Блок finally можно использовать для выполнения кода независимо от возникновения исключения. Такая ситуация необходима в некоторых случаях, поскольку код, следующий после конструкции try/catch не будет выполнен при возникновении исключения. Блок try следует использовать с блоком catch либо finally; в него может входить несколько блоков catch. Пример.

--

Оператор try без catch или finally вызовет ошибку компилятора.

Catch Blocks

A catch block can specify an exception type to catch. This type is called an exception filter, and must be either the Exception type, or derived from this type. Application-defined exceptions should derive from ApplicationException.

Multiple catch blocks with different exception filters can be chained together. Multiple catch blocks are evaluated from top to bottom, but only one catch block is executed for each exception thrown. The first catch block that species the exact type or a base class of the thrown exception will be executed. If no catch block specifies a matching exception filter, a catch block without a filter (if any) will be executed. It is important to position catch blocks with the most specific, that is, the most derived, exception classes first.

You should catch exceptions when the following conditions are true:

  • You have a specific understanding of why the exception was thrown, and can implement a specific recovery, such as catching a FileNotFoundException object and prompting the user to enter a new file name.

  • You can create and throw a new, more specific exception. For example:

    int GetInt(int[] array, int index)

    {

    try

    {

    return array[index];

    }

    catch(System.IndexOutOfRangeException e)

    {

    throw new System.ArgumentOutOfRangeException(

    "Parameter index is out of range.");

    }

    }

  • To partially handle an exception. For example, a catch block could be used to add an entry to an error log, but then re-throw the exception to enable subsequent handling of the exception. For example:

try

{

// try to access a resource

}

catch (System.UnauthorizedAccessException e)

{

LogError(e); // call a custom error logging procedure

throw e; // re-throw the error

}

Блоки catch

Блок catch указывает тип перехватываемого исключения. Этот тип называется фильтром исключений, он должен меть тип Exception либо быть его производным. Исключения, определенные приложением, должны быть производными от ApplicationException.

Несколько блоков catch с различными фильтрами исключений могут быть соединены друг с другом. Вычисление нескольких блоков catch осуществляется сверху вниз, однако для каждого вызванного исключения выполняется только один блок catch. Выполняется первый блок catch, указывающий точный тип или базовый класс созданного исключения. Если блок catch, указывающий соответствующий фильтр исключения, отсутствует, будет выполнен блок catch без фильтра (если таковой имеется). Очень важно, чтобы первыми были размещены блоки catch с самыми конкретными производными классами исключений.

Перехват исключений возможен при выполнении следующих условий.

  • Понимание причины возникновения исключения и реализация особого восстановления, например перехват объекта FileNotFoundException и вывод запроса на ввод нового имени файла.

  • Возможность создания и вызова нового, более конкретного исключения. Пример.

-----

  • Частичная обработка исключения. Например, блок catch можно использовать для добавления записи в журнал ошибок, но затем нужно повторно вызвать исключение, чтобы выполнить его последующую обработку. Пример.

------

Finally Blocks

A finally block enables clean-up of actions performed in a try block. If present, the finally block executes after the try and catch blocks execute. A finally block is always executed, regardless of whether an exception is thrown or whether a catch block matching the exception type is found.

The finally block can be used to release resources such as file streams, database connections, and graphics handles without waiting for the garbage collector in the runtime to finalize the objects.

In this example, the finally block is used to close a file opened in the try block. Notice that the state of the file handle is checked before it is closed. If the try block did not open the file, the file handle will still be set to null. Alternatively, if the file is opened successfully and no exception is thrown, the finally block will still be executed and will close the open file.

System.IO.FileStream file = null;

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

try

{

file = fileinfo.OpenWrite();

file.WriteByte(0xF);

}

finally

{

// check for null because OpenWrite

// might have failed

if (file != null)

{

file.Close();

}

}