C# Exception InnerException

Description

Exception InnerException gets the Exception instance that caused the current exception.

Syntax

Exception.InnerException has the following syntax.


public Exception InnerException { get; }

Example

The following example demonstrates throwing and catching an exception that references an inner exception.


//from www  .j av  a2  s .  c  om
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);
         }
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version