×

c# · level 2 · unit 6 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.