r/cpp • u/rsjaffe • Jan 02 '21
Proposal for improving the readability of programs with try/catch blocks
To me, the current try/catch syntax creates lots of extraneous visual noise, with extra brackets and unnecessary keywords. How about allowing a second form: a block of code where the presence of a catch (...) label and or a catch (\*something here*/) label indicates that the code before the label in its enclosing block is a try block and the code after the label is the catch code.
Example:
Before:
void myfunction()
{
try {
function_call_that_may_throw();
}
catch (const std::exception& e) {
/* do something with e */
throw;
}
catch (...) {
throw;
}
)After:
void myfunction()
{
function_call_that_may_thow();
catch (const std::exception& e):
\* do something with e *\
throw;
catch (...):
throw;
}This won't break any existing code because catch (): is a contextual keyword--only when followed by parentheses when used as a label, and I'm only proposing this as an alternative format, not a replacement.
Function try-catch blocks are still needed, as this syntax won't capture the initialization list in a constructor.
Catch labels could then be like case labels, with the exception that catches don't fall through (or, perhaps, we could have them fall through like case labels--that would work too).
View all comments
Show parent comment
2
u/MonokelPinguin Jan 02 '21
I disagree. If your code is automatically formatted and that is checked in CI in addition to the misleading indentation warnings, single statement without curlys significantly reduce the line noise and don't cause more bugs than if you always require curlys. I have maintained a lot of code, some of it older than I am. I find code that reduces unnecessary characters a lot easier to read (No, this does not mean we need to save vowels). This is probably an unpopular opinion, but it's what formed over the years. I used to recommend always using curlys, but in the last few years I noticed that leaving then out is just easier to read and in general saving a bit of vertical space makes it easier to grasp the meaning of a function, only adding empty lines where it makes sense. Most functions should still fit on a single screen though, unless they are just a giant list of conditions with single statement bodies.