logo search
CSharp_Prog_Guide

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

Блок 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:

try

{

// try to access a resource

}

catch (System.UnauthorizedAccessException e)

{

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

throw e; // re-throw the error

}