StackOverflowException Clase

Definición

Excepción que se produce cuando la pila de ejecución supera el tamaño de la pila. Esta clase no puede heredarse.

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
Herencia
StackOverflowException
Atributos

Ejemplos

En el ejemplo siguiente se usa un contador para asegurarse de que el número de llamadas recursivas al Execute método no supere un máximo definido por la constante 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

Comentarios

StackOverflowException se produce para errores de desbordamiento de pila de ejecución, normalmente en el caso de una recursividad muy profunda o sin enlazar. Por lo tanto, asegúrese de que el código no tiene un bucle infinito ni una recursividad infinita.

StackOverflowException usa el COR_E_STACKOVERFLOW HRESULT, que tiene el valor 0x800703E9. La Localloc instrucción de lenguaje intermedio (IL) produce StackOverflowException. Para obtener una lista de los valores de propiedad iniciales de un StackOverflowException objeto, vea los StackOverflowException constructores.

A partir de .NET Framework 2.0, no se puede capturar un StackOverflowException objeto con un try/catch bloque y el proceso correspondiente finaliza de forma predeterminada. Por lo tanto, debe escribir el código para detectar y evitar un desbordamiento de pila. Por ejemplo, si la aplicación depende de la recursividad, usa un contador o una condición de estado para finalizar el bucle recursivo. Consulte la sección Ejemplos para obtener una ilustración de esta técnica.

Nota

Aplicar el HandleProcessCorruptedStateExceptionsAttribute atributo a un método que produce un StackOverflowException no tiene ningún efecto. Todavía no puede controlar la excepción del código de usuario.

Si la aplicación hospeda Common Language Runtime (CLR), puede especificar que CLR debe descargar el dominio de aplicación donde se produce la excepción de desbordamiento de pila y permitir que el proceso correspondiente continúe. Para obtener más información, vea ICLRPolicyManager Interface.

Constructores

StackOverflowException()

Inicializa una nueva instancia de la StackOverflowException clase , estableciendo la Message propiedad de la nueva instancia en un mensaje proporcionado por el sistema que describe el error, como "La operación solicitada provocó un desbordamiento de pila". Este mensaje tiene en cuenta la referencia cultural del sistema actual.

StackOverflowException(String)

Inicializa una nueva instancia de la clase StackOverflowException con el mensaje de error especificado.

StackOverflowException(String, Exception)

Inicializa una nueva instancia de la clase StackOverflowException con el mensaje de error especificado y una referencia a la excepción interna que representa la causa de esta excepción.

Propiedades

Data

Obtiene una colección de pares clave/valor que proporciona información definida por el usuario adicional sobre la excepción.

(Heredado de Exception)
HelpLink

Obtiene o establece un vínculo al archivo de ayuda asociado a esta excepción.

(Heredado de Exception)
HResult

Obtiene o establece HRESULT, un valor numérico codificado que se asigna a una excepción específica.

(Heredado de Exception)
InnerException

Obtiene la instancia Exception que produjo la excepción actual.

(Heredado de Exception)
Message

Obtiene un mensaje que describe la excepción actual.

(Heredado de Exception)
Source

Devuelve o establece el nombre de la aplicación o del objeto que generó el error.

(Heredado de Exception)
StackTrace

Obtiene una representación de cadena de los marcos inmediatos en la pila de llamadas.

(Heredado de Exception)
TargetSite

Obtiene el método que produjo la excepción actual.

(Heredado de Exception)

Métodos

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetBaseException()

Cuando se invalida en una clase derivada, devuelve la clase Exception que representa la causa principal de una o más excepciones posteriores.

(Heredado de Exception)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetObjectData(SerializationInfo, StreamingContext)
Obsoletos.

Cuando se invalida en una clase derivada, establece SerializationInfo con información sobre la excepción.

(Heredado de Exception)
GetType()

Obtiene el tipo de tiempo de ejecución de la instancia actual.

(Heredado de Exception)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Crea y devuelve una representación de cadena de la excepción actual.

(Heredado de Exception)

Eventos

SerializeObjectState
Obsoletos.

Ocurre cuando una excepción se serializa para crear un objeto de estado de excepción que contenga datos serializados sobre la excepción.

(Heredado de Exception)

Se aplica a

Consulte también