isocpp / isocpp/CppCoreGuidelines

Suggestion for rule about function try blocks of constructors/destructors

Open
#1,196 11 comments 0 reactions 1 assignee View on GitHub

@BjarneStroustrup is already working on this.

Since May 14, 2018.

Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

I have a suggestion for an additional rule regarding function try blocks for constructors/destructors. As [except.handling]/14 [1] states that if control flow reaches the end of a handler of a constructor’s/destructor’s function try block, the handled exception is rethrown. To me (and I think for others it might be too) this case is surprising and therefore I suggest to always state this behavior explicitly (at least in the case mentioned), i.e. insert a throw; or return statement at the end of all handlers of constructor’s/destructor’s function try block. I'm curious whether others consider this as an issue too.

[1] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4741.pdf

Possible rule:

E.XX: Explicitly throw at end of constructor’s/destructor’s function try block

Reason:

If controlflow reaches the end of a constructor's/destructor’s handler of a function try block the handled exception will be implicitly rethrown. The behavior is different in any other catch handler. Therefore, the desired behavior should be stated explicitly in this case.

Example, bad:
struct Resource {
    Resource() noexcept(false) try
    {
        allocationThatMightThrow();
    }
    catch (const AllocationException & e)
    {
        doSomeCleanup(e);
    }
};
Example:
struct Resource {
    Resource() noexcept(false) try
    {
        allocationThatMightThrow();
    }
    catch (const AllocationException& e)
    {
        doSomeCleanup(e);
        throw;
    }
};
Enforcement:

Flag catch handlers of a constructor’s function try block without explicit throw statement. Flag catch handlers of a destructor’s function try block without explicit return or throw statement.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.