typestar

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

  1. int.Parse throws on bad input; the typed catch names that failure.
  2. finally runs on success and failure alike.
  3. The loop survives the bad element and keeps processing.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Errors & files, step 25 of 29 in Language basics.

← Previous Next →

Try & catch in other languages