Kaixuan Li - 2026-11-17

Hi,

Cppcheck reports an error for the "exception dispatcher" idiom when the try { throw; } is not the first statement of the function:

#include <exception>
#include <string>

std::string describeCurrentException() {
    if (!std::current_exception())
        return "no exception";
    try {
        throw;
    } catch (const std::exception& e) {
        return e.what();
    } catch (...) {
        return "unknown exception";
    }
}
$ cppcheck -q rethrow.cpp
rethrow.cpp:8:9: error: Rethrowing current exception with 'throw;', it seems there is no current exception to rethrow. If there is no current exception this calls std::terminate(). More: https://isocpp.org/wiki/faq/exceptions#throw-without-an-object [rethrowNoCurrentException]
        throw;
        ^

The code checks std::current_exception() just before the rethrow, so there is always a current exception here. Without the if guard, the same function produces no warning.

A dispatcher written as a lambda gets the same error:

#include <exception>
#include <string>

int runTask(void (*task)(), std::string& error) {
    auto describe = []() -> std::string {
        try {
            throw;
        } catch (const std::exception& e) {
            return e.what();
        } catch (...) {
            return "unknown exception";
        }
    };
    try {
        task();
    } catch (...) {
        error = describe();
        return 1;
    }
    return 0;
}
$ cppcheck -q rethrow_lambda.cpp
rethrow_lambda.cpp:7:13: error: Rethrowing current exception with 'throw;', it seems there is no current exception to rethrow. If there is no current exception this calls std::terminate(). More: https://isocpp.org/wiki/faq/exceptions#throw-without-an-object [rethrowNoCurrentException]
            throw;
            ^

It looks like the exemption in CheckExceptionSafetyImpl::rethrowNoCurrentException() (lib/checkexceptionsafety.cpp:384) only matches try { throw ; } catch ( at functionScope->bodyStart->next() of a named function. Any statement before the try disables the exemption, and lambdas have no Function, so they are scanned as part of the enclosing function.

Reproduced with 2.20.1 and current main (530e59f).