Learn C# · lesson 44 of 61 · about 9 minutes
Exceptions
Visit the trader: catch errors with try and catch, clean up with finally, and throw your own exceptions.
What you'll learn
- Catch specific exceptions
- Use finally
- Throw exceptions with helpful messages
The trader
A trader at camp makes an offer for each thing in the bag: 15 gold for a gem, 3 for rope and 4 for a torch. Appraise(thing) returns the offer, but two things can go wrong. The key is needed for a quest, so it throws the battle's own QuestItemException, a more specific kind of ArgumentException; anything else the trader doesn't want throws a plain ArgumentException. The camp catches the specific one first and says the key is kept, catches the rest and prints the message, and counts every thing in finally, whatever happened.
When things go wrong
An exception stops normal flow and jumps to the nearest matching catch.
try { ... } catch (FormatException) { ... }handles one kind- Put specific catches before general ones;
catch (Exception e)catches everything finally { ... }always runs, error or notthrow new ArgumentException("why")reports a problem in your own codee.Messageholds the description
If nothing catches it, the program crashes with that message.
Catching one kind of error
try
{
int n = int.Parse("seven");
Console.WriteLine(n);
}
catch (FormatException)
{
Console.WriteLine("That isn't a number");
}Output
That isn't a numberMore about exceptions
One try can have several catch blocks, and C# runs the first one whose type matches, so the most specific goes first. finally runs after the try or the catch, which makes it the place for anything that must happen either way.
Safe division
string[] inputs = { "12", "zero", "0" };
foreach (string text in inputs)
{
try
{
int n = int.Parse(text);
Console.WriteLine($"100 / {n} = {100 / n}");
}
catch (FormatException)
{
Console.WriteLine($"'{text}' isn't a number");
}
catch (DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("--");
}
}Output
100 / 12 = 8
--
'zero' isn't a number
--
Attempted to divide by zero.
--Your own exceptions
An exception is a class, so you can make your own by inheriting from one that's already there, and pass the message to base(message). Because QuestItemException : ArgumentException, a catch (ArgumentException) would catch it too, which is why its own catch must come first.
A cursed item
try
{
throw new CursedException("the amulet is cursed");
}
catch (CursedException e)
{
Console.WriteLine($"Cursed: {e.Message}");
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
class CursedException : ArgumentException
{
public CursedException(string message) : base(message) { }
}Output
Cursed: the amulet is cursedNow try it yourself
This lesson is free in Codiqo, with 9 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.