Compiler-Generated Exceptions 


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



ЗНАЕТЕ ЛИ ВЫ?

Compiler-Generated Exceptions



Some exceptions are thrown automatically by the.NET Framework's common language runtime (CLR) when basic operations fail. These exceptions and their error conditions are listed in the following table.

Exception Description
ArithmeticException A base class for exceptions that occur during arithmetic operations, such as DivideByZeroException and OverflowException.
ArrayTypeMismatchException Thrown when an array cannot store a given element because the actual type of the element is incompatible with the actual type of the array.
DivideByZeroException Thrown when an attempt is made to divide an integral value by zero.
IndexOutOfRangeException Thrown when an attempt is made to index an array when the index is less than zero or outside the bounds of the array.
InvalidCastException Thrown when an explicit conversion from a base type to an interface or to a derived type fails at runtime.
NullReferenceException Thrown when you attempt to reference an object whose value is null.
OutOfMemoryException Thrown when an attempt to allocate memory using the new operator fails. This indicates that the memory available to the common language runtime has been exhausted.
OverflowException Thrown when an arithmetic operation in a checked context overflows.
StackOverflowException Thrown when the execution stack is exhausted by having too many pending method calls; usually indicates a very deep or infinite recursion.
TypeInitializationException Thrown when a static constructor throws an exception and no compatible catch clause exists to catch it.

Исключения, создаваемые компилятором

Некоторые исключения автоматически создаются средой CLR приложения платформы.NET Framework, когда происходит сбой основной операции. Эти исключения и условия их возникновения перечислены в следующей таблице.

Исключение Описание
ArithmeticException Основной класс исключений, происходящих при выполнении арифметических операций, таких как DivideByZeroException и OverflowException.
ArrayTypeMismatchException Создается, когда массив не может хранить данный элемент, поскольку фактический тип элемента несовместим с фактическим типом массива.
DivideByZeroException Создается при попытке разделить целое число на ноль.
IndexOutOfRangeException Создается при попытке индексирования массива, если индекс меньше нуля или выходит за границы массива.
InvalidCastException Создается, когда происходит сбой явного преобразования из основного типа в интерфейс либо в производный тип во время выполнения.
NullReferenceException Создается при попытке ссылки на объект, значение которого равно null.
OutOfMemoryException Создается при неудаче попытки выделения памяти с помощью оператора new. Это означает, что память, доступная для среды выполнения, уже исчерпана.
OverflowException Создается при переполнении арифметической операции в контексте checked.
StackOverflowException Создается, когда стек выполнения переполнен за счет слишком большого количества вызовов отложенных методов; обычно является признаком очень глубокой или бесконечной рекурсии.
TypeInitializationException Создается, когда статический конструктор создает исключение, и не существует ни одного совместимого предложения catch для его захвата.

 


How to: Handle an Exception Using try/catch

The purpose of a try-catch block is to catch and handle an exception generated by working code. Some exceptions can be handled in a catch block and the problem solved without the exception being re-thrown; however, more often the only thing that you can do is make sure that the appropriate exception is thrown.

Example

In this example, IndexOutOfRangeException is not the most appropriate exception: ArgumentOutOfRangeException makes more sense for the method because the error is caused by the index argument passed in by the caller.

class TestTryCatch { static int GetInt(int[] array, int index) { try { return array[index]; } catch (System.IndexOutOfRangeException e) // CS0168 { System.Console.WriteLine(e.Message); //set IndexOutOfRangeException to the new exception's InnerException throw new System.ArgumentOutOfRangeException("index parameter is out of range.", e); } } }

Comments

The code that causes an exception is enclosed in the try block. A catch statement is added immediately after to handle IndexOutOfRangeException, if it occurs. The catch block handles the IndexOutOfRangeException and throws the more appropriate ArgumentOutOfRangeException exception instead. In order to provide the caller with as much information as possible, consider specifying the original exception as the InnerException of the new exception. Because the InnerException property is readonly, you must assign it in the constructor of the new exception.



Поделиться:


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

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