System.Exception Class
Represents error conditions that prevent the execution of the current method and all subsequent methods in the call stack.
Syntax
public abstract class Exception : System.Runtime.Serialization.ISerializable
{
// Constructors
public Exception();
public Exception(string message);
public Exception(string message, Exception innerException);
// Properties
public virtual string Message { get; }
public virtual Exception InnerException { get; }
public virtual string StackTrace { get; }
public virtual string HelpLink { get; set; }
public virtual string Source { get; set; }
// Methods
public virtual Exception GetBaseException();
// Other methods...
}
Remarks
The System.Exception
class is the base class for all exception classes in the .NET Framework.
It is used to signal errors that occur during program execution. When an error occurs, an exception
is thrown, which interrupts the normal flow of the program. You can then handle the exception using
a try-catch
block.
Key properties of the Exception
class include:
Message
: A description of the error.InnerException
: The exception that caused the current exception. This is useful for preserving the original exception information when re-throwing an exception.StackTrace
: A string representation of the call stack at the time the exception was thrown.
System.Exception
class. This allows for more precise error handling.
Inheritance Hierarchy
System.Object
> System.Exception
Thread Safety
Public static members of this type are thread-safe. Any instance members are not guaranteed to be thread-safe.
Example Usage
The following example demonstrates how to catch a DivideByZeroException
, which derives from
System.Exception
, and display its properties.
try
{
int zero = 0;
int result = 10 / zero; // This will throw a DivideByZeroException
}
catch (DivideByZeroException ex)
{
// Log the exception or display an error message
Console.WriteLine($"An error occurred: {ex.Message}");
Console.WriteLine($"Stack Trace: {ex.StackTrace}");
}
catch (Exception ex)
{
// Handle other potential exceptions
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}