Custom Exception Classes

Make your own error types

Posted by Rodrigo Castro on December 2, 2024

C# lets you create your own exception classes for specific error types.

🛠️ Defining a Custom Exception

1
2
3
4
class NegativeNumberException : Exception
{
    public NegativeNumberException(string message) : base(message) { }
}

🏷️ Using Your Exception

1
2
3
4
5
void AcceptOnlyPositive(int n)
{
    if (n < 0)
        throw new NegativeNumberException("Number must be positive.");
}

🛡️ Catching Your Exception

1
2
3
4
5
6
7
8
try
{
    AcceptOnlyPositive(-5);
}
catch (NegativeNumberException ex)
{
    Console.WriteLine(ex.Message); // "Number must be positive."
}

💡 When to Create Custom Exceptions

  • When you want to signal a specific error in your app.
  • When you need to distinguish your errors from others.

Next: Exception best practices!