c# · level 2 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Seat 5 does not exist. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
try
{
Console.WriteLine("Start");
int[] seats = { 0, 0, 0 };
seats[5] = 1;
}
catch (FormatException)
{
Console.WriteLine("Bad number");
}
catch (Exception)
{
Console.WriteLine("Something else");
}
finally
{
Console.WriteLine("Done");
}
your turn
Your turn. Share the taxi fare.
Gwecode types 0. On line 13, catch the exception for dividing by zero. On line 17, add the block that always runs. Press run.
output
press run to see what happens
fix it
The catches are in the wrong order. Fix it!
output
press run to see what happens
- C# says
CS0160on line 14: a previous catch already catches everything this one could. - The catch-all on line 10 swallows every exception, so the
FormatExceptioncatch could never run. - Swap the two catch blocks so
catch (FormatException)comes first, then press run.
nailed it
every problem has its place. :D
- The first matching catch wins.
- The catch-all
catch (Exception)goes last. finallyalways runs.
new words in your collection
- catch-all
- finally
This lesson isn’t saved. A free account remembers every lesson you finish.