Biblioteca de clases de .NET Framework
Exception.InnerException (Propiedad)

Obtiene la instancia de Exception que causó la excepción actual.

Espacio de nombres: System
Ensamblado: mscorlib (en mscorlib.dll)

Sintaxis

Visual Basic (Declaración)
Public ReadOnly Property InnerException As Exception
Visual Basic (Uso)
Dim instance As Exception
Dim value As Exception

value = instance.InnerException
C#
public Exception InnerException { get; }
C++
public:
virtual property Exception^ InnerException {
    Exception^ get () sealed;
}
J#
/** @property */
public final Exception get_InnerException ()
JScript
public final function get InnerException () : Exception

Valor de propiedad

Instancia de Exception que describe el error que causó la excepción actual. La propiedad InnerException devuelve el mismo valor que se pasó al constructor o una referencia nula (Nothing en Visual Basic) si no se suministró el valor de la excepción interna al constructor. Esta propiedad es de sólo lectura.
Comentarios

Cuando se produce una excepción X como resultado directo de una excepción anterior Y, la propiedad InnerException 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.

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

Supongamos que existe una función que lee un archivo y aplica formato a los datos del mismo. En este ejemplo, cuando el código intenta leer el archivo, se produce IOException. La función detecta IOException y produce FileNotFoundException. IOException puede guardarse en la propiedad InnerException de FileNotFoundException de forma que permita examinar las causas del error inicial al código que detecta FileNotFoundException.

La propiedad InnerException, que contiene una referencia a la excepción interna, se establece cuando se inicializa el objeto Exception.

Ejemplo

En el siguiente ejemplo, se muestra la forma de produce y detectar una excepción que hace referencia a una excepción interna.

Visual Basic
Imports System

Public Class MyAppException
   Inherits ApplicationException
   
   Public Sub New(message As [String])
      MyBase.New(message)
   End Sub 'New
   
   Public Sub New(message As [String], inner As Exception)
      MyBase.New(message, inner)
   End Sub 'New
End Class 'MyAppException

Public Class ExceptExample
   
   Public Sub ThrowInner()
      Throw New MyAppException("ExceptExample inner exception")
   End Sub 'ThrowInner
   
   Public Sub CatchInner()
      Try
         Me.ThrowInner()
      Catch e As Exception
         Throw New MyAppException("Error caused by trying ThrowInner.", e)
      End Try
   End Sub 'CatchInner
End Class 'ExceptExample

Public Class Test
   
   Public Shared Sub Main()
      Dim testInstance As New ExceptExample()
      Try
         testInstance.CatchInner()
      Catch e As Exception
         Console.WriteLine("In Main catch block. Caught: {0}", e.Message)
         Console.WriteLine("Inner Exception is {0}", e.InnerException)
      End Try
   End Sub 'Main
End Class 'Test
C#
using System;
public class MyAppException:ApplicationException 
{
   public MyAppException (String message) : base (message) 
   {}
   public MyAppException (String message, Exception inner) : base(message,inner) {}    
   }
public class ExceptExample 
{
   public void ThrowInner () 
   {
   throw new MyAppException("ExceptExample inner exception");
   }
   public void CatchInner() 
   {
      try 
      {
      this.ThrowInner();
      }
         catch (Exception e) 
         {
         throw new MyAppException("Error caused by trying ThrowInner.",e);
         }
      }
   }
public class Test 
{
   public static void Main() 
   {
   ExceptExample testInstance = new ExceptExample();
      try 
      {
      testInstance.CatchInner();
      }
         catch(Exception e) 
         {
         Console.WriteLine ("In Main catch block. Caught: {0}", e.Message);
         Console.WriteLine ("Inner Exception is {0}",e.InnerException);
         }
      }
}
C++
using namespace System;
public ref class MyAppException: public ApplicationException
{
public:
   MyAppException( String^ message )
      : ApplicationException( message )
   {}

   MyAppException( String^ message, Exception^ inner )
      : ApplicationException( message, inner )
   {}

};

public ref class ExceptExample
{
public:
   void ThrowInner()
   {
      throw gcnew MyAppException( "ExceptExample inner exception" );
   }

   void CatchInner()
   {
      try
      {
         this->ThrowInner();
      }
      catch ( Exception^ e ) 
      {
         throw gcnew MyAppException( "Error caused by trying ThrowInner.",e );
      }

   }

};

int main()
{
   ExceptExample^ testInstance = gcnew ExceptExample;
   try
   {
      testInstance->CatchInner();
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "In Main catch block. Caught: {0}", e->Message );
      Console::WriteLine( "Inner Exception is {0}", e->InnerException );
   }

}
J#
import System.*;
public class MyAppException extends ApplicationException
{
    public MyAppException(String message)
    {
      super(message);
    } //MyAppException

    public MyAppException(String message, System.Exception inner)
    {
      super(message, inner);
    } //MyAppException
} //MyAppException

public class ExceptExample
{
    public void ThrowInner()throws MyAppException
    {
        throw new MyAppException("ExceptExample inner exception");
    } //ThrowInner

    public void CatchInner()throws MyAppException
    {
        try {
            this.ThrowInner();
        }
        catch (System.Exception e) {
            throw new MyAppException("Error caused by trying ThrowInner.", e);
        }
    } //CatchInner
} //ExceptExample

public class Test
{
    public static void main(String[] args)
    {
        ExceptExample testInstance = new ExceptExample();
        try {
            testInstance.CatchInner();
        }
        catch (System.Exception e) {
            Console.WriteLine("In main catch block. Caught: {0}", 
                e.get_Message());
            Console.WriteLine("Inner Exception is {0}", 
                e.get_InnerException());
        }
    } //main
} //Test

Este código genera el siguiente resultado:

In Main
  catch block. Caught: Error caused by trying ThrowInner. Inner Exception is
  MyAppException: ExceptExample inner exception at ExceptExample.ThrowInner() at
  ExceptExample.CatchInner()
Plataformas

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition

.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.

Información de versión

.NET Framework

Compatible con: 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 2.0, 1.0
Vea también

Etiquetas :


Page view tracker