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).
9
u/staletic reddit thinks /u/_bstaletic is a bot Jan 02 '21
function-try blocks already exist:
void f() try {
this_might_throw();
} catch (const std::exception& e) {
/* do something with e */
throw;
} catch(...) {
throw;
}1
u/rsjaffe Jan 02 '21 edited Jan 02 '21
My proposal doesn’t replace function try blocks and I see two very different use cases: function try blocks being needed to catch exceptions in constructor initialization lists.
I've edited my post--I had omitted the enclosing function so I see how it started to look like a function-try block--that's not what I meant.
3
u/staletic reddit thinks /u/_bstaletic is a bot Jan 02 '21
I see no reason why your free function shouldn't use a
function-tryblock. Your example still encloses the entire function body in atryblock.
13
u/sphere991 Jan 02 '21
The only thing I really find annoying about try/catch blocks is that if I want to only catch exceptions around a specific function, that returns something, it's awkward to deal with that result:
void some_func(...) {
try {
auto r = foo();
} catch (E const& e) {
// do something meaningful
}
// can't use r here
}So you have to either enclose more in the try block than you'd ideally want to or declare r outside of the try block. Neither of which is great.
This proposal doesn't help me with that problem at all.
But how much does it help in general? The above example becomes:
void some_func(...) {
{
auto r = foo();
catch (E const& e):
// do something meaningful
}
// can't use r here
}Which looks... nearly identical? If I want the try to encompass the whole function body, then I save a single indent?
void some_func(...) {
auto r = foo();
// use r here
catch (E const& e):
// do something meaningful
}I'm not sure this buys you much.
2
u/rsjaffe Jan 02 '21
Yeah, the more I look at what I wrote, the less I like my idea. But the current syntax is annoying.
5
u/NotUniqueOrSpecial Jan 02 '21
Depending on what your "something meaningful" is (in my case it's almost always doing some logging related to the failure), you could use function-try blocks like:
#include <iostream> #include <system_error> int foo() { throw std::runtime_error("Not implemented"); } void bar() try { int n = foo(); std::cout << n << std::endl; } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; } int main() { bar(); }I've never actually worked on a codebase where people did that, but I think it actually looks pretty clean.
4
u/adnukator Jan 02 '21
Function try blocks don't really make any sense outside constructors. This is literally just saving an opening and closing brace at the cost making the code look kind of alien. The moment you want to do anything outside the try-catch blocks, you have to switch to a regular try-catch anyway
2
Jan 03 '21
Function try blocks don't really make any sense outside constructors. This is literally just saving an opening and closing brace at the cost making the code look kind of alien.
I am sympathetic here.
But they definitely make sense for constructors, so the construct needs to exist, and the only reason it looks alien to us is because we don't see it in reading code.
I have never actually used a function try block - in fact, I struggle to remember if I have seen it even once in real-world code.
But I could get used to it.
0
u/sphere991 Jan 02 '21
Right, like I said:
So you have to either enclose more in the try block than you'd ideally want to [...]
This is choosing to enclose the entire function body. Which is fine if that's what you want, but not fine if really you just want to catch something
foo()might throw.
5
u/stinos Jan 02 '21
There are a lot of rules in C++, some less obvious and counterintuitive but things like 'brackets create a scope' are uniform and clear. Derailing from that simple thing with something much less clear ('scope of the hidden try is between last opening bracket and catch :, 'scope of catch : is until next catch : or next closing bracket) and at the same time introducing again new syntax, for no other reason then being able to skip typing some brackets: no thanks :)
3
u/rsjaffe Jan 02 '21
Yeah, I agree. I've quickly realized it was a bad idea, but perhaps I should not delete the post. It'll be a cautionary signpost for later people with similar ideas.
2
u/joemaniaci Jan 02 '21
Are you aware of the function/try/catch syntax?
1
u/rsjaffe Jan 02 '21 edited Jan 02 '21
I've edited my post--I had omitted the enclosing function so I see how it started to look like a function-try block--that's not what I meant.
2
3
u/MonokelPinguin Jan 02 '21
I often try to do something similar, only to remember it does not work. I'd not get rid of the try, I'd just take the old syntax and make the curly brackets optional. That would be like what you can do with if, for and while already anyway, and in theory you could mix and match as necessary.
4
u/erichkeane Clang Maintainer(Templates), EWG Chair Jan 02 '21
FWIW, this is something I wouldn't mind. Currently 'try' must be followed by a compound statement, but I'm not sure I see the necessity for that. Having the catch take any statement as well might be nice too. So:
try something(); catch(ExceptTy) foo(); catch(...) bar();might be nice...
1
u/MonokelPinguin Jan 03 '21
Yep, that's what I had in mind. That probably does not work for function level catch blocks and such, but inside of a function it would feel pretty natural.
3
u/zeGolem83 Jan 02 '21
That would indeed make code a lot more readable...
Something like:
try auto &x = some_function(); catch (...) { .... }1
Jan 03 '21
If you really don't want the extra vertical space, is your example really so much more readable than:
try { auto &x = some_function(); } catch (...) { .... }that it requires us to change the language?
23
u/Skoparov Jan 02 '21
You can say the same about a lot of things in C++, but it's not python and the current syntax is consistent with that of the rest of the language and is explicit in it's intent.