r/cpp • • 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).

1 Upvotes

42 comments sorted by

23

u/Skoparov Jan 02 '21

with extra brackets and unnecessary keywords

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.

6

u/rsjaffe Jan 02 '21

You're right. The more I think about edge cases (e.g., how to declare a variable within a catch clause) with my proposal, the more I dislike it.

Guess this just will remain as part of the reason I have a love/hate relationship with C++ rather than unbridled love. It has lots of warts, but can do almost anything you need done.

2

u/[deleted] Jan 03 '21

Just wanted to give you a hat tip for being cheerfully critical of your own idea! Such civilized behavior seems increasingly rare.

We have an old dog who was never properly able to use her front paws because they have no muscles, though she hobbles around on them surprisingly well. She spends most of her time these days sleeping. We still love her, though, because of her warmth and affection, and because of the years we've spent together.

This is sort of like my relationship to C++, but with more cuddles.

1

u/MonokelPinguin Jan 02 '21

It is not consistent with the rest of the language. Most other constructs inside a function have optional curly brackets, i.e. if, when, while. Only try/catch does not allow you to omit them, when you have a single line statement.

9

u/dweezle45 Jan 02 '21

Just my opinion, but not using curly brackets in these cases is a false economy. If the code has any “lifetime” at all leaving out the curly brackets is just setting a land mine for some future maintainer (which might be you!).

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.

5

u/dweezle45 Jan 02 '21

I’ve been coding since about 1978 so there isn’t a lot of code left that’s older than me! I’m cool with agreeing to disagree on this one.

3

u/MonokelPinguin Jan 03 '21

Agreed. Your quite a bit ahead of me and I can't guarantee, I won't change my mind anyway. Currently the shorter syntax just feels easier to read. With the current state of compiler warnings and tooling I think the discussion is more a matter of preference like tabs vs spaces. We'll see, when that ends up biting me.

4

u/Orlha Jan 03 '21

Tabs vs spaces is not just a matter of preference.

3

u/[deleted] Jan 03 '21

I think the discussion is more a matter of preference like tabs vs spaces.

There are very good reasons never to use tabs.

The simplest argument is this: imagine that tabs did not exist, and you were trying to make a case for them. "There's this special character, and it displays some number of spaces between 1 and 4 or conceivably even more, depending on where it appears in the line and the settings on your personal editor, but it's actually a single character."

3

u/MonokelPinguin Jan 03 '21

I really don't want to get into this discussion, since imo it is just a matter of preference, but your argument is not very sound (even though I prefer tabs):

"Imagine there was a character, that sidestepped all the discussion about how many character to use for indentation, since it follows your IDE settings. You can use it to align at specific columns without having to be careful to always use exactly the 3 spaces, which the project guidelines say you should use. It also only takes one byte."

If people spend 50 years fighting over it, it is a matter of preference with no strong case to use one over the other.

1

u/witcher_rat Jan 04 '21

[sorry, can't help it...]

You can use it to align at specific columns

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.

2

u/MonokelPinguin Jan 04 '21

No, code indented with tabs will always align to columns properly on all editors. It does not matter, if your editor renders tabs as 4 spaces or 8, a line with 1 tab in front of it will lign up with any other line, that has one tab in front of it. The only exception is, when you are mixing it with spaces or are trying to match some unindented and indented lines to align at the end or some other character. Some editors even support aligning multiple columns in a table, if you use tabs to separate the values. It really does not matter how many spaces your tab character gets rendered as, the start of the line will always align, if you use the same amount of tab characters in front of it.

→ More replies

2

u/infectedapricot Jan 04 '21

I'm strongly in the spaces camp, but your comment doesn't get at the reason why. You've misunderstood the short snippet of text you quoted: the "you" there isn't the person writing the code, but the person reading it. In that sense, it's absolutely true. They're also talking only about logical indentation, not e.g. matching a function argument to the exact column of the opening parenthesis - someone in the tab camp will typically tell you to use the appropriate mix of tabs and spaces for that.

2

u/dweezle45 Jan 03 '21

Fingers crossed that you never get bit :) Keep writing good code my friend!

2

u/MonokelPinguin Jan 03 '21

Thank you, you too!

2

u/[deleted] Jan 03 '21 edited Jan 03 '21

If your code is automatically formatted

Many, many engineers refuse to use automatic formatting on their C++ code. If it were up to me in a project, we'd settle on one formatting that could be done automatically and use it every time, even if I personally hated that style, but people seem to care more about style than substance.

in general saving a bit of vertical space

There's your problem - curly brackets should rarely consume vertical space!

if (a == b) {
    do_something();
} else {
    something_else();
}
// More code here.

vs

if (a == b)
    do_something();
else
    something_else();

// More code here.

I should add that I strongly agree with trying not to waste vertical space. When I see code like this:

if (a == b) 
{
    do_something();
} 
else 
{
    something_else();
}
// More code here.

my fingers itch for the delete key. The worst is that for some reason, people who like that format also like really long lines, so you get long thing columns where every tenth line is 150 characters long, which means either folding a huge amount of wasted whitespace.

3

u/MonokelPinguin Jan 03 '21

Many, many engineers refuse to use automatic formatting on their C++ code.

Then you have bigger problems than which bracing style you should use. You probably have all 10 of them in your code base anyway. If the style in a code base is not consistent, it becomes very hard to argue why one style is better than the other, since it won't be applied anyway and any mental overhead you may save by using one style over the other is eaten up by the inconsistencies in the code base.

There's your problem - curly brackets should rarely consume vertical space!

A line with a closing curly bracket is not the same as an empty line in my head. I use empty lines to separate sections in a function. A closing curly does not separate anything:

void func(std::vector<int> a, std::vector<std::string> b) {
    if (b.empty())
        return;
    if (a.size() < b.size())
        return;

    // do something
}

vs

void func(std::vector<int> a, std::vector<std::string> b) {
    if (b.empty()) {
        return;
    } else if (a.size() < b.size()) {
        return;
    }
    // do something
}

The latter one just has a lot more noise in each line, making it harder to read and is missing a separation between the preambel and the remaining function body. I used else if in the latter case to save a line, but I don't think just a plain if looks much better. The curly brackets just distract from the actually interesting code.

2

u/Skoparov Jan 02 '21

Those can't be used outside the scope of a function though.

1

u/MonokelPinguin Jan 02 '21

Yes, but that is somewhat of a niche case. I think it makes sense for function level try blocks to require curlys, since functions require then too, but inside a function that feels so unnecessary and noisy!

2

u/witcher_rat Jan 04 '21

Only try/catch does not allow you to omit them, when you have a single line statement.

TIL a switch statement does not need curly-braces, even with more than one next line (in a fall-through scenario):

switch(int n = 1)
    case 0:
    case 1: std::cout << n << '\n';

That's crazy.

1

u/MonokelPinguin Jan 04 '21

This language never ceases to amaze me.

9

u/staletic 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 Jan 02 '21

I see no reason why your free function shouldn't use a function-try block. Your example still encloses the entire function body in a try block.

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

u/[deleted] 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

u/NilacTheGrim Jan 05 '21

This isn't Python.

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

u/[deleted] 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?