logo
CSharp_Prog_Guide

Блоки finally

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

Блок finally можно использовать для высвобождения ресурсов, например потоков данных, подключений к базам данных, графических дескрипторов, не ожидая финализации объектов сборщиком мусора в среде выполнения.

В этом примере блок finally используется для закрытия файла, открытого в блоке try. Обратите внимание, что состояние дескриптора файла проверяется до его закрытия. Если блок try не открыл файл, дескриптор файла по-прежнему будет иметь значение null. Если файл был успешно открыт и исключение не возникло, блок finally будет выполнен и закроет открытый файл.

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();

}

}

Creating and Throwing Exceptions

Exceptions are used to indicate that an error has occurred while running the program. Exception objects that describe an error are created and then thrown with the throw keyword. The runtime then searches for the most compatible exception handler.

Programmers should throw exceptions when one or more of the following conditions are true:

For example, if a parameter to a method has an invalid value:

static void CopyObject(SampleClass original)

{

if (original == null)

{

throw new System.ArgumentException("Parameter cannot be null", "original");

}

}

One example might be trying to write to a read-only file. In cases where an object state does not allow an operation, throw an instance of InvalidOperationException or an object based on a derivation of this class. This is an example of a method that throws an InvalidOperationException object:

class ProgramLog

{

System.IO.FileStream logFile = null;

void OpenLog(System.IO.FileInfo fileName, System.IO.FileMode mode) {}

void WriteLog()

{

if (!this.logFile.CanWrite)

{

throw new System.InvalidOperationException("Logfile cannot be read-only");

}

// Else write data to the log and return.

}

}