C# Exception GetBaseException

Description

Exception GetBaseException when overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

Syntax

Exception.GetBaseException has the following syntax.


public virtual Exception GetBaseException()

Returns

Exception.GetBaseException method returns The first exception thrown in a chain of exceptions. If the InnerException property of the current exception is a null reference (Nothing in Visual Basic), this property returns the current exception.

Example

The code shows the use of the GetBaseException method to retrieve the original exception.


/*  w  w  w  . ja v  a 2s.  co m*/
using System;


// Define two derived exceptions to demonstrate nested exceptions. 
class SecondLevelException : Exception
{
    public SecondLevelException( string message, Exception inner )
        : base( message, inner )
    { }
}
class ThirdLevelException : Exception
{
    public ThirdLevelException( string message, Exception inner ) 
        : base( message, inner )
    { }
}

class NestedExceptions
{
    public static void Main() 
    {
        try
        {
            try
            {
                throw new SecondLevelException( 
                    "Forced a division by 0 and threw " +
                    "a second exception.", new Exception("test") );

            }
            catch( Exception ex )
            {
                throw new ThirdLevelException( 
                    "Caught the second exception and " +
                    "threw a third in response.", ex );
            }
        }
        catch( Exception ex )
        {
            Exception current;
            current = ex;
            while( current != null )
            {
                Console.WriteLine( current.ToString( ) );
                current = current.InnerException;
            }

            Console.WriteLine( "Display the base exception " +
                "using the GetBaseException method:\n" );
            Console.WriteLine( 
                ex.GetBaseException( ).ToString( ) );
        }
    }
}

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