×

c# · level 2 · unit 6 · lesson 2

  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

Several catches, and a that always runs.

One try block can have several catch blocks, one per kind of problem. C# checks them from the top and runs only the first that matches. Here, box 7 does not exist, so the array gives an IndexOutOfRangeException.

catch (Exception e) is a : every kind of exception matches it, so it must come last. Put it first and C# refuses with CS0160, because the catches below could never run.

A finally block runs after the try and any catch, problem or not. Use it for tidying up that must always happen, like putting a lid back on.

using System;

int[] boxes = { 12, 30, 9 };
try
{
    int pick = int.Parse("7");
    Console.WriteLine($"Box {pick} holds {boxes[pick]}");
}
catch (FormatException)
{
    Console.WriteLine("That is not a number");
}
catch (Exception e)
{
    Console.WriteLine($"Something else went wrong: {e.Message}");
}
finally
{
    Console.WriteLine("Lid back on the box.");
}

Order the catches from most particular to most general.