StackOverflowException Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Исключение, возникающее при превышении размера стека выполнения. Этот класс не наследуется.
public ref class StackOverflowException sealed : SystemException
public sealed class StackOverflowException : SystemException
[System.Serializable]
public sealed class StackOverflowException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class StackOverflowException : SystemException
type StackOverflowException = class
inherit SystemException
[<System.Serializable>]
type StackOverflowException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type StackOverflowException = class
inherit SystemException
Public NotInheritable Class StackOverflowException
Inherits SystemException
- Наследование
- Атрибуты
Примеры
В следующем примере используется счетчик, чтобы убедиться, что количество рекурсивных вызовов Execute метода не превышает максимум, определенный константой MAX_RECURSIVE_CALLS.
using System;
public class Example
{
private const int MAX_RECURSIVE_CALLS = 1000;
static int ctr = 0;
public static void Main()
{
Example ex = new Example();
ex.Execute();
Console.WriteLine("\nThe call counter: {0}", ctr);
}
private void Execute()
{
ctr++;
if (ctr % 50 == 0)
Console.WriteLine("Call number {0} to the Execute method", ctr);
if (ctr <= MAX_RECURSIVE_CALLS)
Execute();
ctr--;
}
}
// The example displays the following output:
// Call number 50 to the Execute method
// Call number 100 to the Execute method
// Call number 150 to the Execute method
// Call number 200 to the Execute method
// Call number 250 to the Execute method
// Call number 300 to the Execute method
// Call number 350 to the Execute method
// Call number 400 to the Execute method
// Call number 450 to the Execute method
// Call number 500 to the Execute method
// Call number 550 to the Execute method
// Call number 600 to the Execute method
// Call number 650 to the Execute method
// Call number 700 to the Execute method
// Call number 750 to the Execute method
// Call number 800 to the Execute method
// Call number 850 to the Execute method
// Call number 900 to the Execute method
// Call number 950 to the Execute method
// Call number 1000 to the Execute method
//
// The call counter: 0
let MAX_RECURSIVE_CALLS = 1000
let mutable ctr = 0
let rec execute () =
ctr <- ctr + 1
if ctr % 50 = 0 then
printfn $"Call number {ctr} to the Execute method"
if ctr <= MAX_RECURSIVE_CALLS then
execute ()
ctr <- ctr - 1
execute ()
printfn $"\nThe call counter: {ctr}"
// The example displays the following output:
// Call number 50 to the Execute method
// Call number 100 to the Execute method
// Call number 150 to the Execute method
// Call number 200 to the Execute method
// Call number 250 to the Execute method
// Call number 300 to the Execute method
// Call number 350 to the Execute method
// Call number 400 to the Execute method
// Call number 450 to the Execute method
// Call number 500 to the Execute method
// Call number 550 to the Execute method
// Call number 600 to the Execute method
// Call number 650 to the Execute method
// Call number 700 to the Execute method
// Call number 750 to the Execute method
// Call number 800 to the Execute method
// Call number 850 to the Execute method
// Call number 900 to the Execute method
// Call number 950 to the Execute method
// Call number 1000 to the Execute method
//
// The call counter: 0
Module Example
Private Const MAX_RECURSIVE_CALLS As Integer = 1000
Dim ctr As Integer = 0
Public Sub Main()
Execute()
Console.WriteLine()
Console.WriteLine("The call counter: {0}", ctr)
End Sub
Private Sub Execute()
ctr += 1
If ctr Mod 50 = 0 Then
Console.WriteLine("Call number {0} to the Execute method", ctr)
End If
If ctr <= MAX_RECURSIVE_CALLS Then
Execute()
End If
ctr -= 1
End Sub
End Module
' The example displays the following output:
' Call number 50 to the Execute method
' Call number 100 to the Execute method
' Call number 150 to the Execute method
' Call number 200 to the Execute method
' Call number 250 to the Execute method
' Call number 300 to the Execute method
' Call number 350 to the Execute method
' Call number 400 to the Execute method
' Call number 450 to the Execute method
' Call number 500 to the Execute method
' Call number 550 to the Execute method
' Call number 600 to the Execute method
' Call number 650 to the Execute method
' Call number 700 to the Execute method
' Call number 750 to the Execute method
' Call number 800 to the Execute method
' Call number 850 to the Execute method
' Call number 900 to the Execute method
' Call number 950 to the Execute method
' Call number 1000 to the Execute method
'
' The call counter: 0
Комментарии
StackOverflowException Вызывается для ошибок переполнения стека выполнения, как правило, в случае очень глубокой или несвязанной рекурсии. Поэтому убедитесь, что код не имеет бесконечного цикла или бесконечного рекурсии.
StackOverflowException использует COR_E_STACKOVERFLOW HRESULT, который имеет значение 0x800703E9. Вызывается LocallocStackOverflowExceptionинструкция промежуточного языка (IL). Список начальных значений свойств для StackOverflowException объекта см. в StackOverflowException конструкторах.
Невозможно поймать StackOverflowException объект с блоком, и соответствующий try/catch процесс завершается по умолчанию. Следовательно, необходимо написать код для обнаружения и предотвращения переполнения стека. Например, если приложение зависит от рекурсии, используйте счетчик или условие состояния для завершения рекурсивного цикла. Иллюстрация этого метода см. в разделе "Примеры ".
Note
Применение атрибута к методу HandleProcessCorruptedStateExceptionsAttribute , который вызывает StackOverflowException отсутствие эффекта. Вы по-прежнему не можете обрабатывать исключение из пользовательского кода.
Если в приложении размещена среда CLR, можно указать, что среда CLR должна выгрузить домен приложения, в котором возникает исключение переполнения стека, и позволить соответствующему процессу продолжить. Дополнительные сведения см. в разделе "Интерфейс ICLRPolicyManager".
Конструкторы
| Имя | Описание |
|---|---|
| StackOverflowException() |
Инициализирует новый экземпляр класса, задав StackOverflowException свойство нового экземпляра Message системным сообщением, описывающим ошибку, например "Запрошенная операция вызвала переполнение стека". Это сообщение учитывает текущий язык и региональные параметры системы. |
| StackOverflowException(String, Exception) |
Инициализирует новый экземпляр StackOverflowException класса с указанным сообщением об ошибке и ссылкой на внутреннее исключение, которое является причиной этого исключения. |
| StackOverflowException(String) |
Инициализирует новый экземпляр StackOverflowException класса с указанным сообщением об ошибке. |
Свойства
| Имя | Описание |
|---|---|
| Data |
Возвращает коллекцию пар "ключ-значение", которые предоставляют дополнительные пользовательские сведения об исключении. (Унаследовано от Exception) |
| HelpLink |
Возвращает или задает ссылку на файл справки, связанный с этим исключением. (Унаследовано от Exception) |
| HResult |
Возвращает или задает HRESULT, закодированное числовое значение, назначенное определенному исключению. (Унаследовано от Exception) |
| InnerException |
Exception Возвращает экземпляр, вызвавшего текущее исключение. (Унаследовано от Exception) |
| Message |
Возвращает сообщение, описывающее текущее исключение. (Унаследовано от Exception) |
| Source |
Возвращает или задает имя приложения или объекта, вызывающего ошибку. (Унаследовано от Exception) |
| StackTrace |
Возвращает строковое представление непосредственных кадров в стеке вызовов. (Унаследовано от Exception) |
| TargetSite |
Возвращает метод, который вызывает текущее исключение. (Унаследовано от Exception) |
Методы
| Имя | Описание |
|---|---|
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetBaseException() |
При переопределении в производном классе возвращает Exception первопричину одного или нескольких последующих исключений. (Унаследовано от Exception) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Устаревшие..
При переопределении в производном классе задает SerializationInfo с информацией об исключении. (Унаследовано от Exception) |
| GetType() |
Возвращает тип среды выполнения текущего экземпляра. (Унаследовано от Exception) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Создает и возвращает строковое представление текущего исключения. (Унаследовано от Exception) |
События
| Имя | Описание |
|---|---|
| SerializeObjectState |
Устаревшие..
Происходит при сериализации исключения для создания объекта состояния исключения, содержащего сериализованные данные об исключении. (Унаследовано от Exception) |