Throwing and custom exceptions
A custom exception
A new exception type is a class that derives from Exception; the BCL hierarchy is Exception at the root, then SystemException and ApplicationException, and every concrete error below them. A library that reports its own failures defines its own type so that a caller can catch those failures and nothing else:
try
{
Load("missing.txt");
}
catch (StorageException e)
{
Console.WriteLine($"message: {e.Message}");
Console.WriteLine($"inner: {e.InnerException?.Message}");
Console.WriteLine($"type: {e.GetType().Name}");
}
Console.WriteLine("done");
static void Load(string name)
{
try
{
throw new FileNotFoundException($"no file {name}");
}
catch (Exception inner)
{
throw new StorageException($"cannot load {name}", inner);
}
}
class StorageException : Exception
{
public StorageException(string message, Exception inner)
: base(message, inner)
{
}
}
dotnet run
message: cannot load missing.txt
inner: no file missing.txt
type: StorageException
done
The type names the layer that failed and the inner exception keeps the cause, which is the pattern for every wrapper: a reader sees one message and a debugger can walk to the original. A custom exception needs three constructors in a library that may be caught across a boundary: the parameterless one, the one with a message and the one with a message and an inner exception.
InnerException
InnerException is the link a wrapper leaves to the original failure, and the runtime prints it in a stack trace. Three rules follow:
- Wrap when the cause belongs to another layer (a file error from the storage layer, a parse error from the wire format) and the caller should not need to know that layer.
- Rethrow with throw; when nothing is added, so the original type and trace survive.
- Never lose the inner exception by creating a new one with only a message; the cause is the part that takes an hour to find again.
Data on the exception
An exception type may carry properties of its own, which is how a caller decides what to do without parsing the message text:
try
{
Check(-3);
}
catch (RangeException e)
{
Console.WriteLine($"{e.GetType().Name} limit {e.Limit} value {e.Value}");
}
try
{
Check(5);
}
catch (Exception e)
{
Console.WriteLine($"unexpected {e.GetType().Name}");
}
Console.WriteLine("done");
static void Check(int value)
{
if (value < 0 || value > 100)
{
throw new RangeException(value, 0, 100);
}
Console.WriteLine($"ok {value}");
}
class RangeException : Exception
{
public RangeException(int value, int min, int max)
: base($"{value} is outside {min}..{max}")
{
Value = value;
Limit = $"{min}..{max}";
}
public int Value { get; }
public string Limit { get; }
}
dotnet run
RangeException limit 0..100 value -3
ok 5
done
The catch read two properties and never touched the message. The second call was inside the range, so it printed ok 5 and no catch ran. A catch of Exception would also have taken the range error, since every exception derives from it, which is why a specific catch belongs first.
The argument exceptions of the BCL
For a bad argument the BCL has three types, and the runtime puts the parameter name in a property: ArgumentNullException for null, ArgumentOutOfRangeException for a value outside the allowed range and ArgumentException for the rest.
try
{
SetAge(-1);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine($"{e.ParamName} {e.ActualValue}");
}
Console.WriteLine("done");
static void SetAge(int age)
{
if (age < 0)
{
throw new ArgumentOutOfRangeException(nameof(age), age, "age cannot be negative");
}
Console.WriteLine($"age {age}");
}
dotnet run
age -1
done
nameof(age) gives the parameter name as a compile-time string, so a rename keeps it correct. The message of that exception also carries the actual value on a second line; this program reads the property instead, which is the form a log or a test can use without parsing text.
When to throw
- A broken contract: an argument the method cannot work with, a state the object cannot be in. The BCL argument types are the right ones.
- A failure the caller cannot handle locally: a missing file, a network error, a parse error of data from outside.
- Not for an expected branch of normal logic: a lookup that finds nothing returns false or null, which is what TryParse and TryGetValue do. Exceptions cost a stack unwind and are meant to be rare.
- Not to control flow in a loop, and not as a substitute for a return value that the signature already has.
Exercises
- Add the three standard constructors to StorageException and catch one built with only a message.
- Give RangeException a ToString override that includes the value and the limit.
- Replace the ArgumentOutOfRangeException with a TrySetAge that returns false, and compare the two call sites.
- Throw from inside an iterator and catch the exception around the foreach. Which line of the iterator ran last?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What must a custom exception derive from?
Answer
Exception, or a type below it
Only a type derived from Exception can be thrown and caught.
-
What is InnerException for?
Answer
Keeping the original failure that a wrapper caught
It is the link a wrapper leaves to the cause, and the runtime prints it in a trace.
-
What does this program print?
try { throw new Exception("x"); } catch (Exception e) { Console.WriteLine(e.Message); }Answer
x
The Message property holds the text passed to the constructor.
-
Which exception reports an argument outside the allowed range?
Answer
ArgumentOutOfRangeException
Its ParamName and ActualValue properties carry the detail, and it derives from ArgumentException.
-
What does
nameof(age)give?Answer
The text "age", fixed at compile time
It is a compile-time string, so a rename updates it everywhere.
-
What does this program print?
try { throw new InvalidOperationException("a"); } catch (Exception e) { Console.WriteLine(e.GetType().Name); }Answer
InvalidOperationException
GetType reports the runtime type, which is the derived one even in a catch of the base.
-
When should a lookup throw instead of returning a value?
Answer
When the absence is a broken contract, not an expected result
An expected miss belongs in the return type; an exception is for the unexpected.
-
Why does a custom exception carry properties?
Answer
So callers can act on the data without parsing the message
The value and the limit are data; a message is for a person.
-
What does this program print?
Console.WriteLine(T(3)); static int T(int n) { try { return n * 2; } finally { Console.WriteLine("cleanup"); } }Answer
cleanup and then 6
The finally runs while the return is being evaluated and the value is printed after it.
-
Which is a bad use of an exception?
Answer
Ending a loop over a million items when the item is not found
An expected branch in a hot loop costs a stack unwind per item and hides the real error.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev