×

c# · level 2 · unit 6 · lesson 3

  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

raises an exception on purpose.

So far C# has raised every exception for you. Your own code can raise one too. throw stops the method on the spot and hands the problem back to whoever called it: .

An ArgumentException means “you gave me a bad value”, which suits a method guarding its data, like refusing to book -1 seats. The text you pass in becomes e.Message for whoever catches it.

If nobody catches it, the program stops with that exception, as with any crash.

using System;

try
{
    Console.WriteLine(Book(2));
    Console.WriteLine(Book(-1));
}
catch (ArgumentException e)
{
    Console.WriteLine($"Refused: {e.Message}");
}

string Book(int seats)
{
    if (seats < 1)
    {
        throw new ArgumentException("you must book at least 1 seat");
    }
    return $"Booked {seats} seats";
}

throw needs a new exception object, so it is always followed by new.