c# · level 2 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Nobody is catching. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Console.WriteLine(Half(10));
Console.WriteLine(Half(7));
Console.WriteLine(Half(4));
int Half(int n)
{
if (n % 2 != 0)
{
throw new ArgumentException($"{n} is odd");
}
return n / 2;
}
your turn
Your turn. Guard the bike's gears.
On line 17, raise an ArgumentException when the gear is outside 1 to 7, with a message that says why. Press run.
output
press run to see what happens
fix it
The day picker will not build. Fix it!
output
press run to see what happens
- C# says
CS1955on line 17:ArgumentExceptioncannot be used like a method. - An exception is an object, and objects are built with one particular word.
- Change line 17 to
throw new ArgumentException("days go from 1 to 7");, then press run.
nailed it
you can refuse bad values. :D
throw new ArgumentException(...)raises a problem.- The caller catches it and reads
e.Message. - An uncaught throw stops the program.
new words in your collection
- throw
- ArgumentException
This lesson isn’t saved. A free account remembers every lesson you finish.