try, catch and finally

Follow the path through a try block when the code succeeds and when it throws.

Time O(1)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

When a line throws, the rest of the try block is skipped and control jumps to the first matching catch. The finally block runs afterwards in both cases, which makes it the place for clean-up.

Code

try {
    Console.WriteLine("open");
    int x = int.Parse(text);
    Console.WriteLine("parsed " + x);
}
catch (FormatException) {
    Console.WriteLine("bad input");
}
finally {
    Console.WriteLine("close");   // always runs
}

Tips

In the .NET library

using var file = File.OpenRead(path); is shorthand for try/finally with Dispose in the finally. For expected bad input, int.TryParse avoids the exception altogether.