I’m reading Stroustrup’s Programming: Principles and Practice and came across this code:
int main()
try {
// our program
return 0; //0 indicates success
}
catch (exception& e) {
cerr << "error: " <<e.what() <<'\n';
keep_window_open();
return 1; // 1 indicates failure
}
catch (...) {
cerr << "Oops: Unknown exception!\n";
keep_window_open();
return 2; //2 indicates failure
}
At first I thought that the first line called the main function (which contained the heart of the code and was written somewhere else). And then we are just trying to catch errors that might have occurred inside of main(). But if that’s the
case, why does it say “our program” in the try block? This makes me think that
this code is defining main(). But if that’s the case, then where are the bracket
s? That is, why isn’t it int main() { on the first line?
…is just a shorter notation equivalent to…
Why does it exist? Well:
As soon as you see the function, you understand that a try/catch block encompasses all the function content, whereas in the second form you have to scan down to the end to see if there’s anything after the catches. This insight makes it quicker and easier to reason about the exception handling.
With the second notation, another programmer’s more likely to unwittingly insert code before or after the try/catch block, which may invalidate earlier exception handling design. A try/catch block makes it more obvious that “encompassing” exception handling is a deliberate design decision.
It’s more concise.
If you have an existing function and want to add exception handling to it, then using the function try block notation clearly avoids having to indent everything inside the function to continue to comply with normal indentation practices. Indenting an entire function is painful, especially if you observe an 80 (or whatever) character line length and have to manually wrap long lines to get them formatted the way you want. (Similarly, if you had a catch statement then decide to let the exceptions directly reach the caller – obviously more useful for functions other than
main– you can remove the try/catch without needing to unindent thetry { }content.)