System.Exception.InnerException Property

Gets the Exception instance that caused the current exception.

Syntax

public Exception InnerException { get; }

Value

An instance of Exception that describes the error that caused the current Exception.

Remarks

When an exception X is thrown as a direct result of a previous exception Y, the InnerException property of X should contain a reference to Y.

Use the InnerException property to obtain the set of exceptions that led to the current exception.

You can create a new exception that catches an earlier exception. The code that handles the second exception can make use of the additional information from the earlier exception to handle the error more appropriately.

Suppose that there is a function that reads a file and formats the data from that file. In this example, as the code tries to read the file, an System.IO.IOException is thrown. The function catches the System.IO.IOException and throws a System.IO.FileNotFoundException. The System.IO.IOException could be saved in the Exception.InnerException property of the System.IO.FileNotFoundException, enabling the code that catches the System.IO.FileNotFoundException to examine what causes the initial error.

The Exception.InnerException property, which holds a reference to the inner exception, is set upon initialization of the exception object.

Example

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

C# Example

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 output is

Example

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

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0