Общие сведения об исключениях 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Общие сведения об исключениях



Исключения имеют следующие свойства.

· Когда в приложении происходит исключительная ситуация, например деление на ноль или предупреждение о недостаточном объеме памяти, генерируется исключение.

· Следует использовать блок try для заключения в него инструкций, которые могут выдать исключения.

· При возникновении исключения в блоке try поток управления немедленно переходит соответствующему обработчику исключений, если он существует. В языке C# ключевое слово catch используется для определения обработчика исключений.

· Если обработчик для определенного исключения не существует, выполнение программы завершается с сообщением об ошибке.

· Если в блоке catch определяется переменная исключения, ее можно использовать для получения дополнительной информации о типе произошедшего исключения.

· Исключения могут явно генерироваться программной с помощью ключевого слова throw.

· Объекты исключения содержат подробные сведения об ошибке, такие как состояние стека вызовов и текстовое описание ошибки.

· Код в блоке finally выполняется даже в случае возникновения исключения, что позволяет программе освободить ресурсы.

 


Using Exceptions

In C#, errors in the program at run time are propagated through the program by using a mechanism called exceptions. Exceptions are thrown by code that encounters an error and caught by code that can correct the error. Exceptions can be thrown by the.NET Framework common language runtime (CLR) or by code in a program. Once an exception is thrown, it propagates up the call stack until a catch statement for the exception is found. Uncaught exceptions are handled by a generic exception handler provided by the system that displays a dialog box.

Exceptions are represented by classes derived from Exception. This class identifies the type of exception and contains properties that have details about the exception. Throwing an exception involves creating an instance of an exception-derived class, optionally configuring properties of the exception, and then throwing the object by using the throw keyword. For example:

class CustomException: Exception { public CustomException(string message) { } } private static void TestThrow() { CustomException ex = new CustomException("Custom exception in TestThrow()"); throw ex; }

After an exception is thrown, the runtime checks the current statement to see whether it is within a try block. If it is, any catch blocks associated with the try block are checked to see whether they can catch the exception. Catch blocks typically specify exception types; if the type of the catch block is the same type as the exception, or a base class of the exception, the catch block can handle the method. For example:

static void TestCatch() { try { TestThrow(); } catch (System.Exception ex) { System.Console.WriteLine(ex.ToString()); } }

Использование исключений

В языке C# ошибки в программе во время выполнения передаются через программу посредством механизма, называемого исключениями. Исключения создаются кодом, который встречает ошибку и перехватываются кодом, который может исправить ее. Исключения могут создаваться средой CLR платформы.NET Framework или кодом в программе. В случае исключения, оно передается по стеку вызовов пока не будет найден оператор catch для исключения. Не перехваченные исключения обрабатываются универсальным обработчиком исключений, предоставляемым системой, который открывает диалоговое окно.

Исключения представляются посредством классов, производных от Exception. Такой класс устанавливает тип исключения и содержит свойства с подробными сведениями об исключении. При генерации исключения создается экземпляр класса, производного от исключения, настраиваются свойства исключения (необязательно), а затем при помощи ключевого слова throw создается объект. Пример.

ß------

 

 

После генерации исключения среда выполнения проверяет текущий оператор и устанавливает, находится ли он в блоке try. Если это так, то проверяются любые блоки catch, связанные с блоком try, и устанавливается возможность перехвата ими исключения. Как правило, блоки Catch задают тип исключений; если тип блока catch соответствует типу исключения или базовому классу исключения, блок catch сможет обработать метод. Пример.

ß----


If the statement that throws an exception is not within a try block or if the try block that encloses it has no matching catch block, the runtime checks the calling method for a try statement and catch blocks. The runtime continues up the calling stack, searching for a compatible catch block. After the catch block is found and executed, control is passed to the first statement after the catch block.

A try statement can contain more than one catch block. The first catch statement that can handle the exception is executed; any following catch statements, even if they are compatible, are ignored. For example:

static void TestCatch2() { try { TestThrow(); } catch (System.Exception ex) { System.Console.WriteLine(ex.ToString()); // this block will be executed } //catch (System.Exception ex) //{ // System.Console.WriteLine(ex.ToString()); // this block will NOT be executed //}   System.Console.WriteLine("Done"); // this statement is executed after the catch block }

Before the catch block is executed, the try blocks that have been evaluated by the runtime and the try block that contains the compatible catch block, are checked for finally blocks. Finally blocks enable the programmer to clean up any ambiguous state that could be left over from an aborted try block, or to release any external resources (such as graphics handles, database connections or file streams) without waiting for the garbage collector in the runtime to finalize the objects. For example:

 


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

Оператор try может содержать несколько блоков catch. Выполняется первый оператор catch, который может обработать исключение; все последующие операторы catch, даже если они совместимы – пропускаются. Пример.

ß-----

 

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

 


 

static void TestFinally() { System.IO.FileStream file = null; //Change the path to something that works on your machine System.IO.FileInfo fileInfo = new System.IO.FileInfo(@"C:\file.txt"); try { file = fileInfo.OpenWrite(); file.WriteByte(0xF); } finally { // Closing the file allows you to reopen it immediately - otherwise IOException is thrown. if (file!= null) { file.Close(); } } try { file = fileInfo.OpenWrite(); System.Console.WriteLine("OpenWrite() succeeded"); } catch (System.IO.IOException) { System.Console.WriteLine("OpenWrite() failed"); } }

If WriteByte() threw an exception, the code in the second try block that tries to reopen the file would fail if file.Close() is not called, and the file would remain locked. Because finally blocks are executed even if an exception is thrown, the finally block in the previous example allows for the file to be closed correctly and helps avoid an error.

If no compatible catch block is found on the call stack after an exception is thrown, one of three things occurs:

· If the exception is within a destructor, the destructor is aborted and the base destructor, if any, is called.

· If the call stack contains a static constructor, or a static field initializer, a TypeInitializationException is thrown, with the original exception assigned to the InnerException property of the new exception.

· If the start of the thread is reached, the thread is terminated.


 

 

ß----

 

Если WriteByte() сгенерировал исключение, код во втором блоке try, пытающийся повторно открыть файл, не будет выполнен, если file.Close() не вызван, и файл останется заблокированным. Так как блоки finally выполняются даже в случае генерации исключения, блок finally в предыдущем примере предусматривает правильное закрытие файла и помогает избежать ошибок.

Если в стеке вызовов после генерации исключения не удается найти совместимый блок catch, то происходит одно из трех действий.

· Если исключение возникло внутри деструктора, деструктор прерывается и вызывается базовый деструктор, если он имеется.

· Если в стеке вызовов содержится статический конструктор или статический инициализатор поля, генерируется TypeInitializationException и исходное исключение присваивается свойству InnerException нового исключения.

· По достижении начала потока он прерывается.

 


Exception Handling

A try block is used by C# programmers to partition code that may be affected by an exception, and catch blocks are used to handle any resulting exceptions. A finally block can be used to execute code regardless of whether an exception is thrown. This situation is sometimes necessary because code that follows a try/catch construct will not be executed if an exception is thrown. A try block must be used with either a catch or a finally block, and can include multiple catch blocks. For example:

try { // Code to try here. } catch (SomeSpecificException ex) { // Code to handle exception here. // Only catch exceptions you know how to handle. // Never catch base class System.Exception. }
try { // Code to try here. } finally { // Code to execute after try here. }

 

try { // Code to try here. } catch (SomeSpecificException ex) { // Code to handle exception here. } finally { // Code to execute after try (and possibly catch) here. }

A try statement without a catch or finally block will cause a compiler error.


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

Блок 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(); } }

 


Блоки 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(); } }

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 125; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.144.33.41 (0.026 с.)