The base class for all exceptions in the .NET Framework. It provides the fundamental properties and methods needed for error handling and reporting.
System
mscorlib.dll
System.Object → System.Exception
Signature | Description |
---|---|
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. |
Name | Type | Description |
---|---|---|
Message | string | Gets a message that describes the current exception. |
StackTrace | string | Gets a stack trace that provides information about the location where the exception was thrown. |
InnerException | Exception | Gets the exception instance that caused the current exception. |
Data | IDictionary | Gets a collection of user-defined key/value pairs associated with the exception. |
HelpLink | string | Gets or sets a link to the help file associated with this exception. |
Source | string | Gets or sets the name of the application or the object that causes the error. |
HResult | int | Gets or sets coded numeric value assigned to a specific exception. |
Name | Signature | Description |
---|---|---|
GetBaseException | () : Exception | Returns the root cause of one or more subsequent exceptions. |
ToString | () : string | Creates 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. |
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!");
}
}
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.
Exception
unless you intend to rethrow or log it globally.using System.Runtime.Serialization;
when implementing custom serialization.HelpLink
property for user-friendly error references.