Learn C# · lesson 48 of 61 · about 10 minutes
Errors and Testing
Create your own exception type and write simple automated checks for the shop's rules.
What you'll learn
- Define a custom exception
- Throw and catch it with details
- Write small checks that print PASS or FAIL
The dragon armour
The blacksmith's best piece, the dragon armour, costs 100 gold. Shop.Pay(amount) takes a price straight from the purse: it throws an ArgumentException for a price that isn't above 0, and a NotEnoughGoldException, a class of the battle's own, when the purse is too light, with a Needed property and a message saying how much more gold it would take. Then the shop gets a few checks of its own: a fresh test shop with 50 gold, and a Check() that prints PASS or FAIL for each rule, with Throws<T>() to test that the right exception comes out.
Errors that explain themselves
A custom exception is a class that inherits from Exception:
class NotEnoughCoinsException(int needed) : Exception($"Need {needed} more coins") { public int Needed => needed; }
That uses a primary constructor: parameters right after the class name.
Testing: small checks that compare what the code does with what it should do. Real projects use a framework like xUnit, but the idea is the same: arrange, act, assert.
Checks for the wallet
int failures = 0;
void Check(string name, bool passed)
{
Console.WriteLine($"{(passed ? "PASS" : "FAIL")} {name}");
if (!passed) failures++;
}
var w = new Wallet(100);
w.Spend(30);
Check("spending lowers the balance", w.Coins == 70);
try
{
w.Spend(500);
Check("overspending throws", false);
}
catch (NotEnoughCoinsException e)
{
Check("overspending throws", e.Needed == 430);
}
Check("a failed spend changes nothing", w.Coins == 70);
Check("negative amounts are refused", Throws(() => w.Spend(-5)));
Console.WriteLine(failures == 0 ? "All checks passed" : $"{failures} failed");
static bool Throws(Action action)
{
try { action(); return false; }
catch (ArgumentException) { return true; }
}
class NotEnoughCoinsException(int needed) : Exception($"Need {needed} more coins")
{
public int Needed => needed;
}
class Wallet(int coins)
{
public int Coins { get; private set; } = coins;
public void Spend(int amount)
{
if (amount <= 0) throw new ArgumentException("amount must be positive");
if (amount > Coins) throw new NotEnoughCoinsException(amount - Coins);
Coins -= amount;
}
}Output
PASS spending lowers the balance
PASS overspending throws
PASS a failed spend changes nothing
PASS negative amounts are refused
All checks passedTip
Action is a type for "a piece of code to run later". () => w.Spend(-5) is a lambda that takes nothing and does the spend.
One Throws for every exception
static bool Throws<T>(Action action) where T : Exception is generic: T is filled in when it's called, so Throws<NotEnoughGoldException>(...) and Throws<ArgumentException>(...) are the same method checking for different exceptions. where T : Exception promises that T is an exception, which is what lets catch (T) compile. Each Check also returns whether it passed, so counting the failures is one line of LINQ.
A generic check
Console.WriteLine(Throws<FormatException>(() => int.Parse("ten")));
Console.WriteLine(Throws<FormatException>(() => int.Parse("10")));
static bool Throws<T>(Action action) where T : Exception
{
try
{
action();
return false;
}
catch (T)
{
return true;
}
}Output
True
FalseNow try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.