C# Custom Exceptions
A custom exception is an exception class a program defines for its own errors. Its name states the exact problem that occurred.
Throw a custom exception
CheckAge throws TooYoungException for an age under 18. The catch block prints the stored message.
using System;
class TooYoungException : Exception
{
public TooYoungException(string message) : base(message)
{
}
}
class Program
{
static void CheckAge(int age)
{
if (age < 18)
{
throw new TooYoungException("Age " + age + " is too young");
}
Console.WriteLine("Age accepted");
}
static void Main(string[] args)
{
try
{
CheckAge(15);
}
catch (TooYoungException ex)
{
Console.WriteLine(ex.Message);
}
}
}An age that passes
An age of 21 passes the check inside the try block. No exception is thrown, so the catch block stays unused.
using System;
class TooYoungException : Exception
{
public TooYoungException(string message) : base(message)
{
}
}
class Program
{
static void CheckAge(int age)
{
if (age < 18)
{
throw new TooYoungException("Age " + age + " is too young");
}
Console.WriteLine("Age accepted");
}
static void Main(string[] args)
{
try
{
CheckAge(21);
}
catch (TooYoungException ex)
{
Console.WriteLine(ex.Message);
}
}
}Catch with a prefix
The catch block adds its own words before the message. The stored message stays unchanged.
using System;
class TooYoungException : Exception
{
public TooYoungException(string message) : base(message)
{
}
}
class Program
{
static void CheckAge(int age)
{
if (age < 18)
{
throw new TooYoungException("Age " + age + " is too young");
}
Console.WriteLine("Age accepted");
}
static void Main(string[] args)
{
try
{
CheckAge(12);
}
catch (TooYoungException ex)
{
Console.WriteLine("Blocked: " + ex.Message);
}
}
}Example
using System;
class TooYoungException : Exception
{
public TooYoungException(string message) : base(message)
{
}
}
class Program
{
static void CheckAge(int age)
{
if (age < 18)
{
throw new TooYoungException("Age " + age + " is too young");
}
Console.WriteLine("Age accepted");
}
static void Main(string[] args)
{
try
{
CheckAge(16);
}
catch (TooYoungException ex)
{
Console.WriteLine("Signup refused: " + ex.Message);
}
}
}Key points
- A custom exception class inherits from Exception.
- The class name ends with the word Exception.
- Its constructor passes the message to the base class.
- The base call stores the text in the Message property.
- A method throws the new type with the throw keyword.
- A catch block can name the custom type on its own.
In this example, CheckAge rejects an age of 16 with a TooYoungException. The message travels through the base constructor into the Message property. The catch block prints the refusal line with that message.
Note
One custom type per problem keeps each catch block clear.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does TooYoungException pass its message to the Exception base class?