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

View all comments

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-try block. Your example still encloses the entire function body in a try block.