StackOverflowException Classe

Definição

A exceção é lançada quando a pilha de execução ultrapassa o tamanho da pilha. Esta classe não pode ser herdada.

public ref class StackOverflowException sealed : SystemException
[System.Serializable]
public sealed class StackOverflowException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class StackOverflowException : SystemException
public sealed class StackOverflowException : SystemException
[<System.Serializable>]
type StackOverflowException = class
    inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type StackOverflowException = class
    inherit SystemException
type StackOverflowException = class
    inherit SystemException
Public NotInheritable Class StackOverflowException
Inherits SystemException
Herança
StackOverflowException
Atributos

Exemplos

O exemplo seguinte utiliza um contador para garantir que o número de chamadas recursivas ao Execute método não exceda um máximo definido pela 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

Observações

StackOverflowException é lançado para erros de overflow de stack de execução, normalmente em caso de recursão muito profunda ou ilimitada. Por isso, certifica-te de que o teu código não tem um loop infinito ou recursão infinita.

StackOverflowException utiliza o COR_E_STACKOVERFLOW HRESULT, que tem o valor 0x800703E9. A Localloc instrução da língua intermédia (IL) lança StackOverflowException. Para uma lista dos valores iniciais de propriedades de um StackOverflowException objeto, veja os StackOverflowException construtores.

Não consegues apanhar um StackOverflowException objeto com um try/catch bloco, e o processo correspondente é terminado por defeito. Consequentemente, deve escrever o seu código para detetar e evitar um excesso de pilha. Por exemplo, se a sua aplicação depende da recursão, use um contador ou uma condição de estado para terminar o ciclo recursivo. Para uma ilustração desta técnica, consulte a secção Exemplos .

Note

Aplicar o HandleProcessCorruptedStateExceptionsAttribute atributo a um método que lança um StackOverflowException não tem efeito. Ainda assim, não consegues lidar com a exceção do código do utilizador.

Se a sua aplicação hospedar o Common Language Runtime (CLR), pode especificar que o CLR deve descarregar o domínio da aplicação onde ocorre a exceção de excesso de pilha e deixar o processo correspondente continuar. Para mais informações, consulte a Interface ICLRPolicyManager.

Construtores

Name Description
StackOverflowException()

Inicializa uma nova instância da StackOverflowException classe, definindo a Message propriedade da nova instância para uma mensagem fornecida pelo sistema que descreve o erro, como "A operação solicitada causou um overflow de pilha." Esta mensagem tem em conta a cultura atual do sistema.

StackOverflowException(String, Exception)

Inicializa uma nova instância da StackOverflowException classe com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção.

StackOverflowException(String)

Inicializa uma nova instância da StackOverflowException classe com uma mensagem de erro especificada.

Propriedades

Name Description
Data

Obtém uma coleção de pares chave/valor que fornecem informação adicional definida pelo utilizador sobre a exceção.

(Herdado de Exception)
HelpLink

Obtém ou define um link para o ficheiro de ajuda associado a esta exceção.

(Herdado de Exception)
HResult

Recebe ou define HRESULT, um valor numérico codificado atribuído a uma exceção específica.

(Herdado de Exception)
InnerException

Obtém a Exception instância que causou a exceção atual.

(Herdado de Exception)
Message

Recebe uma mensagem que descreve a exceção atual.

(Herdado de Exception)
Source

Obtém ou define o nome do aplicativo ou o objeto que causa o erro.

(Herdado de Exception)
StackTrace

Obtém uma representação string dos frames imediatos na stack de chamadas.

(Herdado de Exception)
TargetSite

Obtém o método que lança a exceção atual.

(Herdado de Exception)

Métodos

Name Description
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetBaseException()

Quando sobrescrito numa classe derivada, devolve o Exception que é a causa raiz de uma ou mais exceções subsequentes.

(Herdado de Exception)
GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Quando sobreposto numa classe derivada, define a SerializationInfo informação com sobre a exceção.

(Herdado de Exception)
GetType()

Obtém o tipo de execução da instância atual.

(Herdado de Exception)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
ToString()

Cria e devolve uma representação string da exceção atual.

(Herdado de Exception)

evento

Name Description
SerializeObjectState

Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção.

(Herdado de Exception)

Aplica-se a

Ver também