try, catch and finally
Follow the path through a try block when the code succeeds and when it throws.
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
- Try the input 42 to see the path with no exception.
- Catch the most specific exception you can handle. A bare catch (Exception) hides bugs.
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.