Skip to content

Clang++ rejects try-catch in discarded if constexpr branch with -fno-exceptions #138939

@zerhud

Description

@zerhud

Summary:
Clang incorrectly rejects code containing a try-catch block inside a discarded if constexpr branch when compiled with -fno-exceptions. The try-catch block should not be evaluated, as it is excluded at compile-time, but Clang emits an error: cannot use 'try' with exceptions disabled.

Steps to Reproduce:

  1. Create a file test.cpp with the following code:
    template<auto enable> void foo(auto&& fnc) {
        if constexpr(enable) try{ fnc(); } catch(...){}
        else fnc();
    }
    
    int main(int, char**) {
        foo<false>([]{});
    }
  2. Compile with:
    clang++ -std=c++20 -fno-exceptions -c test.cpp
  3. Alternatively, see the issue on Godbolt: https://godbolt.org/z/3ecnde5z4

Actual Results:

test.cpp:2:25: error: cannot use 'try' with exceptions disabled
    if constexpr(enable) try{ fnc(); } catch(...){}
                         ^
1 error generated.

Expected Results:
The code should compile successfully, as the try-catch block is in a discarded if constexpr branch and should not be evaluated.

Additional Information:

  • The code compiles successfully with GCC
  • A not called template function with try-catch block rejected too (Godbolt)

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:frontendLanguage frontend issues, e.g. anything involving "Sema"confirmedVerified by a second partyconstexprAnything related to constant evaluationdiverges-from:gccDoes the clang frontend diverge from gcc on this issuegood first issuehttps://github.com/llvm/llvm-project/contribute

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions