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, no sign-in needed to watch.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
}static void parse(String text) {
try {
System.out.println("open");
int x = Integer.parseInt(text);
System.out.println("parsed " + x);
}
catch (NumberFormatException e) {
System.out.println("bad input");
}
finally {
System.out.println("close"); // always runs
}
}void parse(const string& text) {
try {
cout << "open\n";
int x = stoi(text);
cout << "parsed " << x << "\n";
}
catch (const invalid_argument&) {
cout << "bad input\n";
}
cout << "close\n"; // C++ has no finally: cleanup goes after the try (or in a destructor)
}try:
print("open")
x = int(text)
print("parsed", x)
except ValueError:
print("bad input")
finally:
print("close") # always runsTips
- 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.