Custom Errors in C#

Custom errors can be created in C# by implementing the Exception class. Here’s an example that demonstrates this concept:

using System;

// A custom error type usually inherits from Exception
public class ArgException : Exception
{
    public int Arg { get; }

    public ArgException(int arg, string message) : base(message)
    {
        Arg = arg;
    }

    public override string ToString()
    {
        return $"{Arg} - {Message}";
    }
}

public class Program
{
    static int F(int arg)
    {
        if (arg == 42)
        {
            // Throw our custom exception
            throw new ArgException(arg, "can't work with it");
        }
        return arg + 3;
    }

    static void Main()
    {
        try
        {
            F(42);
        }
        catch (ArgException ae)
        {
            Console.WriteLine(ae.Arg);
            Console.WriteLine(ae.Message);
        }
        catch (Exception)
        {
            Console.WriteLine("Exception doesn't match ArgException");
        }
    }
}

In C#, we create custom exceptions by inheriting from the Exception class. Our ArgException class includes an Arg property and overrides the ToString method to provide a custom string representation.

The F method demonstrates throwing our custom exception when a specific condition is met.

In the Main method, we use a try-catch block to handle exceptions. The catch (ArgException ae) block specifically catches our custom exception type, allowing us to access its properties.

To run this program:

$ dotnet run
42
can't work with it

This example demonstrates how to create and use custom exceptions in C#, providing a way to handle specific error conditions in your code.