logo search
CSharp_Prog_Guide

Блоки catch

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

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

}

}