Flip File Zone@Blog

What Did Linus Torvalds Mean When He Called C++ Exceptions "Fundamentally Broken"?

Torvalds' 2004 critique targeted a real flaw: exceptions thrown during stack unwinding trigger std::terminate, plus hidden control flow and implicit allocation—disqualifying for kernels, though widely used safely in application code.

FlipFileZone · TECH GUIDES
shareShare this post
What Did Linus Torvalds Mean When He Called C++ Exceptions "Fundamentally Broken"?

In January 2004, on the Linux kernel mailing list, in the middle of a routine technical thread about whether a kernel module could be compiled with a C++ compiler, Linux creator Linus Torvalds wrote a message that has been quoted in programming discussions ever since. Responding to a suggestion that the kernel was written in C purely out of habit, Torvalds explained that Linux had actually tried C++ once before, back in 1992, and that it hadn't worked out. Among the reasons he listed, one line in particular has outlived the original thread by two decades: the exception handling mechanism in C++ was, in his words, fundamentally broken, and especially broken for kernels.

This article unpacks what Torvalds actually meant by that statement, the specific technical mechanisms in C++ exception handling that justify the concern, why those mechanisms are particularly dangerous inside an operating system kernel specifically (as opposed to ordinary application software), and how the broader systems-programming community has responded to this critique in the two decades since, including in the design of newer kernel-adjacent technologies like Rust.

The Context: A 2004 Mailing List Thread, Not a Formal Paper

It's worth being precise about the source, because the quote is frequently repeated without its original context. The statement appears in a plain-text email reply on the Linux Kernel Mailing List (LKML), not in a published paper, a conference talk, or official kernel documentation. A fellow kernel developer, Bart Samwel, responded in the same thread agreeing with Torvalds and adding a more precise technical explanation: the exception handling mechanism breaks down specifically when an exception is thrown from a destructor during the stack-unwinding process triggered by a different, already-in-flight exception. This detail turns out to be the technical core of the entire critique, and it's worth explaining carefully, because it is a genuinely well-documented and well-understood failure mode in C++, not an idiosyncratic complaint.

The full original email, along with the rest of the thread, remains archived and publicly readable through the Linux Kernel Mailing List archives and is also mirrored on sites that catalog Torvalds' various pointed technical opinions, such as the unofficial but frequently cited harmful.cat-v.org Linus Torvalds C++ archive. Reading the original thread in full is useful, because it makes clear that this was an off-the-cuff technical opinion delivered in the heat of an ongoing engineering disagreement about kernel module development, not a carefully refereed academic claim — a distinction that matters for understanding both its strengths and its limits.

How C++ Exception Handling Actually Works

To understand the critique, it helps to understand the mechanism being criticized. When code executes throw someException;, the C++ runtime does not simply jump to the nearest catch block the way a goto would. Instead, it begins a process called stack unwinding: the runtime walks back up through the chain of function calls that led to the throw, and for each stack frame it passes through, it calls the destructors of any local objects that were fully constructed in that frame, before finally transferring control to a matching catch block, if one exists.

javascript
void inner() {
    std::vector<int> data(1000); // local object with a destructor
    throw std::runtime_error("something went wrong");
    // execution never reaches here
}

void outer() {
    try {
        inner();
    } catch (const std::exception& e) {
        std::cerr << "Caught: " << e.what() << "\n";
    }
}

In this example, when inner() throws, the runtime automatically calls the destructor of data (releasing its underlying heap allocation) as part of unwinding the stack, before control reaches the catch block in outer(). This automatic cleanup is, in ordinary application code, one of C++ exception handling's most celebrated properties — it composes naturally with RAII (Resource Acquisition Is Initialization), ensuring resources are released even when control flow jumps unpredictably due to an error.

The Specific Failure Mode: Exceptions During Unwinding

The danger Torvalds and Samwel were pointing to arises in a more specific and less commonly discussed scenario: what happens if, while the stack is already being unwound because of one exception, a destructor being called as part of that unwinding itself throws a second exception?

javascript
struct Resource {
    ~Resource() {
        throw std::runtime_error("cleanup failed"); // thrown during unwinding!
    }
};

void problematic() {
    Resource r;
    throw std::runtime_error("original error");
    // while unwinding to handle this, r's destructor runs and throws again
}

The C++ standard's answer to "what happens when two exceptions are in flight simultaneously, with no way to know which one the program is supposed to be handling" is to call std::terminate(), which by default aborts the entire program immediately, without running any further cleanup, without unwinding the rest of the stack, and without giving the calling code any opportunity to recover. This is documented behavior, not a bug in any particular compiler, and is described in detail in the C++ standard library reference for std::terminate on cppreference.com. The language's chosen answer to this edge case is, deliberately, "give up entirely," because there is no generally correct way to decide which of two simultaneously active exceptions should take priority.

For an ordinary desktop or server application, an unrecoverable std::terminate() call is bad — the process crashes — but it's a contained, well-understood failure: the operating system reclaims the process's memory, other processes are unaffected, and a crash reporter or supervisor process can often restart the failed program. For an operating system kernel, the calculus is entirely different. The kernel is the thing that's supposed to be managing memory, scheduling processes, and recovering from failures for every other piece of software on the machine. There is no higher-level process supervisor to catch a kernel crash and restart it gracefully; an unrecoverable abort inside kernel code typically means a full system crash (a "kernel panic" or, on some platforms, a "blue screen"), taking down every running program and potentially losing unsaved data across the entire machine. This asymmetry — a contained, recoverable failure in userland versus a catastrophic, unrecoverable failure in kernel space — is the central reason Torvalds and Samwel singled out kernels as a context where this problem is "especially" severe, not merely problematic.

The Hidden Control Flow Problem

A second, related concern embedded in Torvalds' broader critique — visible in the surrounding lines of the same email, where he also objected to compilers and languages that "hide things like memory allocations behind your back" — is that exceptions introduce invisible control-flow paths into code that, by ordinary reading, looks like it can't fail at that point.

javascript
void process(const std::string& name) {
    auto record = lookup(name);   // could this function throw? Reading
                                   // the call site alone doesn't tell you.
    record.update();              // if lookup() threw, this line never runs
    save(record);
}

Unless a function is explicitly marked noexcept (a C++11 addition that arrived seven years after this particular email was written), or unless a reader has memorized the exception-safety guarantees of every function being called, there is no way to tell, just by looking at a line of code, whether execution might suddenly jump elsewhere. In an ordinary application, this is a readability and correctness concern that experienced C++ developers learn to manage through exception-safety conventions (the well-known "basic," "strong," and "no-throw" exception guarantee levels documented extensively in resources like the C++ Core Guidelines' exception safety section). In kernel code, where a function might be holding a spinlock, running with interrupts disabled, or executing in a context where any unexpected control-flow jump could leave hardware state or critical data structures in an inconsistent condition, this same hidden-control-flow property becomes substantially more dangerous, because the kernel cannot tolerate code silently jumping away from a critical section without explicit, auditable cleanup.

Why Kernels Specifically Reject This Mechanism

Kernel code operates under a set of constraints that ordinary application code does not. A few of these are directly relevant to why exception handling, as implemented in mainstream C++ compilers, is considered incompatible with kernel development by virtually every major operating system project, not just Linux:

No fallback if something goes catastrophically wrong. As discussed above, application-level crashes are contained by the operating system; kernel-level crashes generally are not, because the kernel itself is the layer responsible for containment.

Strict, manual control over when memory allocation happens. Kernel code frequently runs in contexts (interrupt handlers, code holding spinlocks, very early boot before memory management is fully initialized) where memory allocation is either disallowed entirely or must use special, restricted allocation paths. The exception-handling runtime in most C++ implementations relies on a support library (commonly libstdc++ or libc++'s unwinding runtime, layered on top of a generic unwinding library such as libunwind or the platform's native unwind tables) that itself performs heap allocation to construct and propagate exception objects — for example, the Itanium C++ ABI's __cxa_allocate_exception function, documented in the Itanium C++ ABI exception handling specification, allocates memory from the heap for most thrown exception objects. A kernel cannot tolerate a hidden, implicit allocation occurring deep inside ordinary-looking code, especially in a context where allocation is supposed to be forbidden.

No standard runtime environment to depend on. The C++ exception-handling machinery depends on a runtime support library, unwind tables embedded in the compiled binary, and often features of the underlying C library that a "freestanding" environment like a kernel — which deliberately avoids depending on a general-purpose C or C++ standard library implementation — does not provide by default. Building and maintaining a kernel-safe reimplementation of this entire runtime, just to support a language feature the kernel otherwise has no need for, is widely seen as not worth the engineering cost.

How the Linux Kernel Actually Handles Errors Instead

Rather than exceptions, the Linux kernel — like most C codebases and most C++ kernels and embedded systems — relies on explicit error codes returned from functions, conventionally negative errno values, checked immediately by the caller, with cleanup performed using goto statements that jump to labeled cleanup sections at the end of a function. This pattern is documented extensively in the official Linux kernel coding style guide, which explicitly recommends the "goto for centralized cleanup" pattern for exactly this reason.

javascript
int do_something(struct device *dev) {
    int ret;
    void *buf = kmalloc(SIZE, GFP_KERNEL);
    if (!buf)
        return -ENOMEM;

    ret = do_step_one(dev, buf);
    if (ret)
        goto cleanup;

    ret = do_step_two(dev, buf);
    if (ret)
        goto cleanup;

    ret = 0;
cleanup:
    kfree(buf);
    return ret;
}

Every place control flow can change is explicit and visible directly in the source: a function call followed immediately by a check of its return value. There is no hidden jump that a reader could miss, and there is no possibility of two simultaneous "in-flight" error conditions colliding the way two simultaneously propagating exceptions can. This pattern is more verbose than a try/catch block, and the verbosity is precisely the tradeoff: explicitness over hidden machinery, at the cost of needing to write (and review) an error check after virtually every fallible function call.

This Concern Is Not Unique to Linux

It's worth noting that the position Torvalds expressed in 2004 is not an isolated or eccentric opinion confined to the Linux kernel community. A broad range of performance-critical and safety-critical software domains have independently reached the same conclusion and codified it as an explicit rule.

Google's internal and widely published C++ Style Guide prohibits the use of C++ exceptions across the large majority of Google's codebase, citing very similar reasoning: the difficulty of reasoning about all possible control-flow paths in large, pre-existing codebases that were never designed with exception safety in mind, and the resulting risk of subtle resource leaks or inconsistent state.

Safety-critical and embedded software standards reach the same conclusion through a different, more formal route. The Joint Strike Fighter Air Vehicle C++ Coding Standards (commonly referred to as "JSF AV C++"), developed for mission- and safety-critical avionics software, explicitly disallow exception handling, citing concerns about unpredictable timing behavior and the difficulty of formally verifying programs with non-local control flow. The MISRA C++ guidelines, widely used in automotive software, similarly impose severe restrictions on exception usage for related reasons.

Perhaps most relevant to the present-day version of this debate is the Rust for Linux project, which has worked since 2022 to introduce Rust as an officially supported second language for writing Linux kernel code, discussed in detail in our companion coverage of whether Rust will eventually replace C++. Rust's own error-handling philosophy for kernel code deliberately avoids unwinding through panic! in most kernel-relevant code paths, instead favoring the Result type for explicit, checked error propagation — a design choice documented in the Rust for Linux project documentation that, notably, arrives at almost the same conclusion as the Linux kernel's existing C convention: errors should be explicit return values checked by the caller, not invisible control-flow jumps, specifically because kernel code cannot tolerate the unwind-and-possibly-abort behavior that exceptions (in C++) or unchecked panics (in Rust) both introduce.

Pushback and the Limits of the Critique

It would be incomplete to present this purely as a settled, universally accepted technical fact, because it isn't treated that way even within the systems-programming community. A detailed 2024 technical discussion on LWN.net, a respected outlet for in-depth Linux kernel coverage, addressing renewed debate over allowing a restricted subset of C++ in the kernel, explicitly pushed back on treating Torvalds' statement as objective fact rather than opinion, noting that it is not a fact but just Linus's opinion, while still agreeing that allowing exceptions in the kernel would create significant problems and that they should remain excluded from any kernel-permitted C++ subset.

This distinction matters. The specific technical mechanism Torvalds and Samwel described — the danger of an exception thrown during unwinding triggering std::terminate, combined with hidden control flow and implicit allocation — is genuine, well-documented, and broadly accepted as a real engineering hazard, particularly in freestanding and kernel environments. What's more debatable is the much stronger, more sweeping framing of the claim — that the mechanism is "fundamentally broken" as a general statement about C++ exceptions in all contexts, rather than specifically unsuitable for kernel and similarly constrained environments. Millions of lines of production application software, web services, and desktop applications use C++ exceptions successfully every day, with experienced teams managing exception safety through well-established conventions; the C++ standards committee itself has continued to refine and extend exception-related language features (such as noexcept specifications and, more recently, ongoing research proposals around alternative error-handling mechanisms like std::expected, added in C++23 partly in response to exactly these long-standing criticisms). The existence of std::expected, documented on cppreference.com, is itself a notable piece of evidence that the broader C++ community has, over the two decades since Torvalds' email, partially converged on the same conclusion he was reaching for: that explicit, checked return-value-style error handling is often preferable to exceptions in exactly the performance-sensitive, predictability-critical contexts where the Linux kernel lives.

Conclusion

When Linus Torvalds called C++ exception handling "fundamentally broken" in that 2004 mailing list email, he was pointing at a specific, technically well-grounded failure mode: the danger of a second exception being thrown while the stack is already unwinding due to a first one, an edge case the C++ standard resolves by calling std::terminate() and aborting the program outright, combined with the broader concerns that exceptions introduce invisible, hard-to-audit control-flow jumps and may rely on hidden memory allocation deep inside the language runtime. For an operating system kernel — software with no higher-level supervisor to catch a crash, strict and context-dependent rules about when memory allocation is even permitted, and an extremely low tolerance for unrecoverable failure — these properties are disqualifying, which is why every major kernel project, not just Linux, has independently converged on avoiding exception-based (or panic-based, in Rust's case) control flow for kernel-critical code. The claim is best understood not as a universal indictment of C++ exceptions for all software everywhere, a stronger and more contestable position, but as a precise, defensible critique of a specific language mechanism's fitness for one of the most demanding and unforgiving programming environments that exists.

Further Reading

shareShare this post

recommendYou may also like
chatPost a comment

Comments

0
For Advertisement, News, Article, Advertorial, Feature etc please contact us:  flipfilezone@gmail.com