Custom exceptions; error design
Create small custom exceptions, pick correct built-in types (ArgumentException, InvalidOperationException), and add context with InnerException.
Purpose & goals
Aim: Make errors clear and catchable.
- Use a specific type for a specific failure
- Good message + InnerException for context
- Prefer built-ins when they fit
Custom exception type
Derive from Exception, end the name with Exception, and add the standard constructors. Carry small, useful data.
using System;
// Custom, specific to our domain
public sealed class ConfigNotFoundException : Exception
{
public string Key { get; private set; }
public ConfigNotFoundException(string key)
: base("Config key not found: " + key)
{
Key = key;
}
public ConfigNotFoundException(string key, Exception inner)
: base("Config key not found: " + key, inner)
{
Key = key;
}
}
public class Program
{
public static void Main(string[] args)
{
try
{
throw new ConfigNotFoundException("ApiUrl");
}
catch (ConfigNotFoundException ex)
{
Console.WriteLine(ex.Message);
}
}
}
All lessons in this course
- try/catch/finally, throw new vs rethrow
- Custom exceptions; error design
- IDisposable, using statement