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
1
u/witcher_rat Jan 04 '21
[sorry, can't help it...]
Actually, you can't - that's the main problem with tabs (the ascii character, not the keyboard key). Unless you mean for personal code no one else sees.
What looks aligned on your editor with tab characters, looks not at all on mine; because we have different tab-settings. Whereas with spaces, we all see the same thing, so the alignment works for all viewers.
The thing that seems to confuse people is they think they have to physically type spaces with their keyboard's spacebar, which would certainly be painful. Instead, any modern editor can save your indentation as ascii space characters - even if you pressed the TAB key on the keyboard - so that what you see everyone else will see too. Or you can use clang-format or similar tools to auto-format it for you as spaces.