c# · level 2 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
the risky part, and what goes wrong.
Some code can fail even when you wrote it well: someone types twelve where you wanted a number. Put the risky lines in a try block. If one of them fails, C# jumps straight to a matching catch block instead of stopping the whole program.
catch (FormatException e) handles only that kind of exception, and e holds the details. is a sentence saying what went wrong. Once the catch block finishes, the program carries on below it.
Lines in the try block after the failing one are skipped, so nothing doubles twelve.
using System;
string[] typed = { "12", "twelve", "7" };
foreach (string text in typed)
{
try
{
int number = int.Parse(text);
Console.WriteLine($"{number} doubled is {number * 2}");
}
catch (FormatException e)
{
Console.WriteLine($"Skipped {text}: {e.Message}");
}
}
Console.WriteLine("Still running!"); If you do not need the details, leave the name out: catch (FormatException).
guess first
One, two, three, four? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
try
{
Console.WriteLine("One");
int n = int.Parse("3.5");
Console.WriteLine("Two");
}
catch (FormatException)
{
Console.WriteLine("Three");
}
Console.WriteLine("Four");
your turn
Your turn. Cope with a word instead of a number.
Gwecode types four as the answer. On line 10, catch the exception int.Parse gives for text like that. On line 12, write a kind message. Press run.
output
press run to see what happens
fix it
One free item crashes the till. Fix it!
output
press run to see what happens
- C# still stops, with
FormatExceptionon line 9. Which kind of exception does the catch on line 11 handle? - A catch only handles the kind of exception it names. Nothing here divides by zero.
- Change
DivideByZeroExceptiontoFormatExceptionon line 11, then press run.
nailed it
your program keeps going after a problem. :D
- Put risky code in
try. - A matching
catchhandles the exception. e.Messagesays what went wrong.
new words in your collection
- try
- catch
- Message
This lesson isn’t saved. A free account remembers every lesson you finish.