C# - Exception base class
In C#, the "exception base class" refers to the foundation of the exception handling mechanism. It's the core concept and set of classes that provide the structure for handling and managing exceptions in C# programs. The base for exceptions is typically represented by the System.Exception
class, from which all other exception classes are derived.
Here's a simplified class hierarchy for exceptions in C#:
System.Object
└── System.Exception
├── System.SystemException
│ ├── System.NullReferenceException
│ ├── System.IndexOutOfRangeException
│ └── ...
└── System.ApplicationException (Obsolete in .NET 2.0 and later; use System.Exception instead)
Example: Handling Exceptions
Here's a simplified explanation with a human-readable code example:
using System;
class Program
{
static void Main()
{
try
{
// Attempt to divide by zero, which will throw an exception
int result = DivideByZero(10, 0);
Console.WriteLine($"Result: {result}");
}
catch (Exception ex)
{
// Catch the exception and handle it
Console.WriteLine($"An exception occurred: {ex.Message}");
}
}
static int DivideByZero(int numerator, int denominator)
{
if (denominator == 0)
{
// Create and throw a custom exception
throw new Exception("Denominator cannot be zero.");
}
return numerator / denominator;
}
}
Explanation of the code:
- In this example, we have a
try
block where we attempt to perform a division operation (DivideByZero(10, 0)
) that will result in an exception because we are trying to divide by zero.
- The
catch
block is used to catch and handle exceptions. In this case, we catch an Exception
object (ex
) that represents the exception that occurred.
- Inside the
DivideByZero
method, we check if the denominator is zero, and if it is, we create and throw a custom exception using throw new Exception("Denominator cannot be zero.")
.
- When an exception is thrown, the program jumps to the
catch
block, where we can handle the exception by displaying a message.
In this example, System.Exception
serves as the base for handling exceptions. It's the fundamental class that allows you to catch and manage different types of exceptions in C# programs. Other exception classes, such as System.ArithmeticException
or System.NullReferenceException
, are derived from System.Exception
, creating a hierarchy of exception types that you can catch and handle as needed.