Try & catch in C#
Catch the exception you expect; let the rest travel.
var inputs = new[] { "10", "zero", "4" };
foreach (var text in inputs)
{
try
{
var n = int.Parse(text);
Console.WriteLine($"100 / {n} = {100 / n}");
}
catch (FormatException)
{
Console.WriteLine($"'{text}' is not a number");
}
finally
{
Console.WriteLine("checked one input");
}
}
How it works
int.Parsethrows on bad input; the typed catch names that failure.finallyruns on success and failure alike.- The loop survives the bad element and keeps processing.
Keywords and builtins used here
catchfinallyforeachinintnewtryvar
The run, in numbers
- Lines
- 18
- Characters to type
- 281
- Tokens
- 66
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 42 seconds.
Step 1 of 3 in Errors & files, step 25 of 29 in Language basics.