C# User-Defined Exceptions

In C#, you can define your own custom exceptions by creating classes that derive from the Exception class or any of its subclasses. This allows you to create specialized exception types that suit your application’s specific needs. Here’s an example of how you can define a custom exception in C#:

using System;

// Custom exception class derived from Exception
public class MyCustomException : Exception
{
    // Constructors
    public MyCustomException() : base() { }

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

    public MyCustomException(string message, Exception innerException) : base(message, innerException) { }

    // You can add additional properties or methods specific to your exception
    // ...
}

In the example above, MyCustomException is a custom exception class derived from the base Exception class. It provides constructors for different scenarios, allowing you to provide an optional error message and an inner exception. You can also add additional properties or methods as needed.

To use your custom exception, you can throw it using the throw keyword and catch it using a try-catch block, just like any other exception. Here’s an example:

public class MyClass
{
    public void SomeMethod()
    {
        try
        {
            // Something goes wrong
            throw new MyCustomException("An error occurred.");
        }
        catch (MyCustomException ex)
        {
            Console.WriteLine("Custom exception caught: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("General exception caught: " + ex.Message);
        }
    }
}

In the code above, SomeMethod() throws a MyCustomException when an error occurs. The exception is then caught in the catch block specific to MyCustomException, allowing you to handle it separately. If you want to catch all exceptions, you can include a catch block for the base Exception class as a fallback.

By defining and using custom exceptions, you can create a more robust and meaningful exception handling mechanism in your C# applications.