Exception.InnerException Propiedad

Definición

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

public:
 property Exception ^ InnerException { Exception ^ get(); };
public Exception InnerException { get; }
public Exception? InnerException { get; }
member this.InnerException : Exception
Public ReadOnly Property InnerException As Exception

Valor de propiedad

Exception

Objeto que describe el error que causó la excepción actual. La propiedad InnerException devuelve el mismo valor que se pasó al constructor Exception(String, Exception) o null si no se suministró el valor de la excepción interna al constructor. Esta propiedad es de sólo lectura.

Implementaciones

Ejemplos

En el ejemplo siguiente se muestra cómo iniciar y detectar una excepción que hace referencia a una excepción interna.

using namespace System;

public ref class AppException: public Exception
{
public:
   AppException(String^ message ) : Exception(message)
   {}

   AppException(String^ message, Exception^ inner) : Exception(message, inner)
   {}
};

public ref class Example
{
public:
   void ThrowInner()
   {
      throw gcnew AppException("Exception in ThrowInner method.");
   }

   void CatchInner()
   {
      try {
         this->ThrowInner();
      }
      catch (AppException^ e) {
         throw gcnew AppException("Error in CatchInner caused by calling the ThrowInner method.", e);
      }
   }
};

int main()
{
   Example^ ex = gcnew Example();
   try {
      ex->CatchInner();
   }
   catch (AppException^ e) {
      Console::WriteLine("In catch block of Main method.");
      Console::WriteLine("Caught: {0}", e->Message);
      if (e->InnerException != nullptr)
         Console::WriteLine("Inner exception: {0}", e->InnerException);
   }
}
// The example displays the following output:
//    In catch block of Main method.
//    Caught: Error in CatchInner caused by calling the ThrowInner method.
//    Inner exception: AppException: Exception in ThrowInner method.
//       at Example.ThrowInner()
//       at Example.CatchInner()
using System;

public class AppException : Exception
{
   public AppException(String message) : base (message)
   {}

   public AppException(String message, Exception inner) : base(message,inner) {}
}

public class Example
{
   public static void Main()
   {
      Example ex = new Example();

      try {
         ex.CatchInner();
      }
      catch(AppException e) {
         Console.WriteLine ("In catch block of Main method.");
         Console.WriteLine("Caught: {0}", e.Message);
         if (e.InnerException != null)
            Console.WriteLine("Inner exception: {0}", e.InnerException);
      }
   }

   public void ThrowInner ()
   {
      throw new AppException("Exception in ThrowInner method.");
   }

   public void CatchInner()
   {
      try {
         this.ThrowInner();
      }
      catch (AppException e) {
         throw new AppException("Error in CatchInner caused by calling the ThrowInner method.", e);
      }
   }
}
// The example displays the following output:
//    In catch block of Main method.
//    Caught: Error in CatchInner caused by calling the ThrowInner method.
//    Inner exception: AppException: Exception in ThrowInner method.
//       at Example.ThrowInner()
//       at Example.CatchInner()
open System

type AppException =
    inherit Exception
    
    new (message: string) = { inherit Exception(message) }

    new (message: string, inner) = { inherit Exception(message, inner) }

let throwInner () =
    raise (AppException "Exception in throwInner function.")
    ()

let catchInner () =
    try
        throwInner ()
    with :? AppException as e ->
        raise (AppException("Error in catchInner caused by calling the throwInner function.", e) )

[<EntryPoint>]
let main _ =
    try
        catchInner ()
    with :? AppException as e ->
        printfn "In with block of main function."
        printfn $"Caught: {e.Message}"
        if e.InnerException <> null then
            printfn $"Inner exception: {e.InnerException}"
    0
// The example displays the following output:
//    In with block of main function.
//    Caught: Error in catchInner caused by calling the throwInner function.
//    Inner exception: Example+AppException: Exception in throwInner function.
//       at Example.throwInner()
//       at Example.catchInner()
Public Class AppException : Inherits Exception
   Public Sub New(message As String)
      MyBase.New(message)
   End Sub
   
   Public Sub New(message As String, inner As Exception)
      MyBase.New(message, inner)
   End Sub
End Class

Public Class Example
   Public Shared Sub Main()
      Dim testInstance As New Example()
      Try
         testInstance.CatchInner()
      Catch e As AppException
         Console.WriteLine ("In catch block of Main method.")
         Console.WriteLine("Caught: {0}", e.Message)
         If e.InnerException IsNot Nothing Then
            Console.WriteLine("Inner exception: {0}", e.InnerException)
         End If
      End Try
   End Sub
   
   Public Sub ThrowInner()
      Throw New AppException("Exception in ThrowInner method.")
   End Sub
   
   Public Sub CatchInner()
      Try
         Me.ThrowInner()
      Catch e As AppException
         Throw New AppException("Error in CatchInner caused by calling the ThrowInner method.", e)
      End Try
   End Sub
End Class
' The example displays the following output:
'    In catch block of Main method.
'    Caught: Error in CatchInner caused by calling the ThrowInner method.
'    Inner exception: AppException: Exception in ThrowInner method.
'       at Example.ThrowInner()
'       at Example.CatchInner()

Comentarios

Cuando se produce una excepción X como resultado directo de una excepción Yanterior, la InnerException propiedad de X debe contener una referencia a Y.

Utilice la propiedad InnerException para obtener el conjunto de excepciones que dieron lugar a la excepción actual.

Puede crear una nueva excepción que capture una excepción anterior. El código que controla la segunda excepción puede hacer uso de la información adicional de la excepción anterior para controlar el error de forma más adecuada.

Supongamos que hay una función que lee un archivo y da formato a los datos de ese archivo. En este ejemplo, como el código intenta leer el archivo, se produce una IOException excepción . La función detecta y IOException produce una FileNotFoundExceptionexcepción . IOException se puede guardar en la InnerException propiedad de FileNotFoundException, lo que permite que el código que capture para FileNotFoundException examinar la causa del error inicial.

La InnerException propiedad , que contiene una referencia a la excepción interna, se establece al inicializar el objeto de excepción.

Se aplica a