.NET Framework Docs

System.Exception Class

The base class for all exceptions in the .NET Framework. It provides the fundamental properties and methods needed for error handling and reporting.

Overview
Members
Examples
Remarks

Namespace

System

Assembly

mscorlib.dll

Inheritance

System.Object → System.Exception

Constructors

SignatureDescription
Exception()Initializes a new instance of the Exception class.
Exception(string message)Initializes a new instance with a specified error message.
Exception(string message, Exception innerException)Initializes a new instance with a specified error message and a reference to the inner exception that is the cause of this exception.
protected Exception(SerializationInfo info, StreamingContext context)Initializes a new instance with serialized data.

Properties

NameTypeDescription
MessagestringGets a message that describes the current exception.
StackTracestringGets a stack trace that provides information about the location where the exception was thrown.
InnerExceptionExceptionGets the exception instance that caused the current exception.
DataIDictionaryGets a collection of user-defined key/value pairs associated with the exception.
HelpLinkstringGets or sets a link to the help file associated with this exception.
SourcestringGets or sets the name of the application or the object that causes the error.
HResultintGets or sets coded numeric value assigned to a specific exception.

Methods

NameSignatureDescription
GetBaseException() : ExceptionReturns the root cause of one or more subsequent exceptions.
ToString() : stringCreates and returns a string representation of the current exception.
GetObjectData(SerializationInfo info, StreamingContext context)Populates a SerializationInfo with the data needed to serialize the target object.

Basic Usage

using System;

class Program
{
    static void Main()
    {
        try
        {
            ThrowError();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Caught exception: {ex.Message}");
            Console.WriteLine($"Source: {ex.Source}");
            Console.WriteLine($"StackTrace:\n{ex.StackTrace}");
        }
    }

    static void ThrowError()
    {
        throw new Exception("Something went wrong!");
    }
}

Custom Exception Derivation

using System;

public class InvalidConfigurationException : Exception
{
    public InvalidConfigurationException() { }

    public InvalidConfigurationException(string message)
        : base(message) { }

    public InvalidConfigurationException(string message, Exception inner)
        : base(message, inner) { }
}

All exceptions in .NET derive from System.Exception. It is recommended to throw the most specific exception type possible and to include clear messages and inner exceptions when rethrowing.