×

c# · level 2 · unit 6 · lesson 1

  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

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).