c# · level 2 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Make an exception named after your own problem.
Built-in exceptions like FormatException describe computer troubles. Your app has its own, like a sold-out cake. A is a class you write and name after the problem. It inherits from Exception, so C# treats it like any other exception.
: base(message) hands the message to the Exception constructor, which stores it in Message. Now code can catch (OutOfStockException e) and handle a sold-out cake differently from every other problem. End each exception's name with Exception, so readers know what it is.
using System;
int left = 0;
try
{
if (left == 0)
{
throw new OutOfStockException("We have no eclairs left.");
}
Console.WriteLine("One eclair, coming up!");
}
catch (OutOfStockException e)
{
Console.WriteLine($"Sorry! {e.Message}");
}
class OutOfStockException : Exception
{
public OutOfStockException(string message) : base(message) { }
} A catch for your own exception ignores every other kind of problem.
guess first
The alarm goes off. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
try
{
Console.WriteLine("Checking the doors...");
throw new AlarmException("Back door open!");
}
catch (AlarmException e)
{
Console.WriteLine(e.Message);
}
catch (Exception)
{
Console.WriteLine("Something else broke.");
}
class AlarmException : Exception
{
public AlarmException(string message) : base(message) { }
}
your turn
Your turn. The show is sold out.
Put your name in the message on line 8. On line 17, build FullyBookedException on Exception. On line 19, pass the message to the base constructor. Press run.
output
press run to see what happens
fix it
The treasure chest lost its message. Fix it!
output
press run to see what happens
- The message printed is C#'s own, not yours. Where does
messagego once the constructor has it? - The constructor receives the message but never hands it on to the
Exceptionconstructor. - Change line 19 to
public WrongCodeException(string message) : base(message) { }, then press run.
nailed it
your app's problems have names. :D
- A custom exception inherits from
Exception. : base(message)passes the message on.- Catch it by name to handle it on its own.
new words in your collection
- custom exception
This lesson isn’t saved. A free account remembers every lesson you finish.