skip to content

When a C++ codebase is built with exceptions disabled, what happens to throw and try, and how do functions report failure instead?

level: juniorimportance: should knowfreq 55%

answer

  1. a compiler dialect, not ISO C++
  2. throw and try stop compiling
  3. failure travels in the return value
  4. from_chars instead of stoi
  5. constructors need a factory

basics

~10 s

Code that writes throw, try or catch no longer compiles. Functions return the failure instead: an error enum or std::error_code, std::optional, or C++23 std::expected, and constructors that can fail become factory functions.

solid answer

~40 s

Turning exceptions off is a compiler dialect, not a mode of ISO C++: Clang rejects the source with `cannot use 'throw' with exceptions disabled` and the same for `try`, and the `__cpp_exceptions` macro is no longer defined. Every failure therefore has to travel in the return value: an error enum, `std::error_code`, `std::optional` when the reason does not matter, or C++23 `std::expected<T, E>`, which carries either the value or the error. Library calls that report by throwing are swapped for ones that report by value, such as `std::from_chars` (C++17) instead of `std::stoi`. A constructor cannot return an error, so a type whose construction can fail gets a private constructor and a static factory returning `std::expected` or `std::optional`. Marking those functions `[[nodiscard]]` turns an ignored error into a compiler warning.

code

cpp · 26 lines
cpp
#include <charconv>
#include <cstdio>
#include <expected>
#include <string_view>

enum class SpeedError { not_a_number, out_of_range, above_limit };

[[nodiscard]] std::expected<int, SpeedError> parse_rpm(std::string_view text) {
  int rpm = 0;
  auto [ptr, ec] = std::from_chars(text.data(), text.data() + text.size(), rpm);
  if (ec == std::errc::invalid_argument) return std::unexpected(SpeedError::not_a_number);
  if (ec == std::errc::result_out_of_range) return std::unexpected(SpeedError::out_of_range);
  if (rpm > 6000) return std::unexpected(SpeedError::above_limit);
  return rpm;
}

int main() {
  for (std::string_view cmd : {"1500", "fast", "9000"}) {
    if (auto rpm = parse_rpm(cmd)) {
      std::printf("set %d rpm\n", *rpm);
    } else {
      std::printf("rejected '%.*s': error %d\n", static_cast<int>(cmd.size()), cmd.data(),
                  static_cast<int>(rpm.error()));
    }
  }
}

go deeper

for a junior

Know that throw and try stop compiling and name the return-value alternatives: error codes, std::optional and std::expected.

for a middle

Explain why a constructor cannot report failure without exceptions and show the factory pattern, plus from_chars in place of stoi.

for a senior

Point out the library calls that still try to throw, such as value() or at(), and how the team keeps ignored error codes from slipping through.

for a principal

Weigh one error type for the whole codebase against per-module error enums, and how errors cross into third-party code that assumes exceptions.

## What switching exceptions off actually does The C++ standard has no exception-free mode. GCC and Clang offer one as a **dialect**: with exceptions disabled the compiler stops generating the unwinding machinery, and it refuses any source that would need it. Compiling a motor-controller module that still contains a `throw` with Apple clang 21 gives: - `error: cannot use 'throw' with exceptions disabled` - `error: cannot use 'try' with exceptions disabled` GCC refuses the same code with its own wording. The compilers also stop defining the feature-test macro `__cpp_exceptions`, so shared headers can test `#if __cpp_exceptions` and pick a non-throwing path. The rest of the core language, such as `noexcept`, destructors, RAII and templates, works as before; the standard library is where behaviour shifts. ## Where the failure goes instead Without exceptions a failure has to travel back through the **return value**. The common shapes: | Shape | Standard | Carries | Typical use | |---|---|---|---| | `bool` or an `enum class` error code | any | success or one reason | hardware drivers, legacy C interfaces | | `std::error_code` | C++11 | a value plus an error category | portable library interfaces | | `std::optional<T>` | C++17 | a value or nothing | "not found" where the reason is obvious | | `std::expected<T, E>` | C++23 | a value or an error of type `E` | most new code that has a C++23 compiler | | out-parameter plus status | any | anything | APIs that must stay C-compatible | `std::expected<T, E>` is the closest replacement for a throwing function: the caller tests it (`if (r)`), reads the value with `*r` and the reason with `r.error()`. Its `value()` member is the one trap, because it reports a missing value by throwing `std::bad_expected_access`; in a build without exceptions that path ends the program instead, so code that runs without exceptions uses `*r` after a check, or `value_or`. ## Library calls that throw Some standard functions report errors only by throwing, and a codebase without exceptions avoids them: 1. **Parsing.** `std::stoi` throws `std::invalid_argument` or `std::out_of_range`. `std::from_chars` (C++17, `<charconv>`) never throws and returns a `std::from_chars_result` whose `ec` member is a `std::errc`. 2. **Checked access.** `std::vector::at` and `std::map::at` throw `std::out_of_range`; a build without exceptions checks the index itself and uses `operator[]`. 3. **Allocation.** A plain `new` reports failure with `std::bad_alloc`; `new (std::nothrow) T` returns a null pointer instead. ## Constructors and other functions with no return value A constructor has no return value to carry an error, and that is the biggest design change. Two patterns cover it: - **Static factory**: make the constructor private and write `static std::expected<Motor, MotorError> Motor::create(...)`, which validates first and constructs only on success. - **Two-phase initialisation**: a constructor that cannot fail plus an `init()` that returns a status. It is older and weaker, because an object can exist in a half-built state. Overloaded operators and destructors have the same problem; the usual answer is to keep them free of failure paths. ## Choosing between the shapes The options are not interchangeable, and the choice is easier made once than per function: - **`std::optional<T>`** is right only when the caller cannot do anything different for different reasons, such as a cache lookup. - **An `enum class` error** is the cheapest and the easiest to switch over; it suits a driver layer whose failures are a short fixed list. - **`std::error_code`** adds a category, so codes from different subsystems (the motor driver, the CAN bus) can travel through one interface without colliding. - **`std::expected<T, E>`** keeps the value and the error in one return object with no heap allocation: it holds either a `T` or an `E` in place, plus a flag. Before C++23 teams wrote or imported an equivalent result type. Whatever is chosen, the error type should not itself be able to fail to construct or copy, or the error path gains error paths of its own. ## Making errors hard to ignore A return code is easy to drop on the floor, which an exception never is. Marking functions `[[nodiscard]]` (C++17) makes the compiler warn when a caller ignores the result, and an `enum class` error type keeps error values from mixing silently with integers. Coding standards for safety firmware, such as MISRA C++, also have rules requiring the value a function returns to be used. ## Example The snippet below parses a speed command for the motor controller with `std::from_chars` and reports through `std::expected`. It builds and runs with exceptions and RTTI both disabled.

  • Why is std::expected::value() risky in a C++ build without exceptions?
    `value()` reports a missing value by throwing `std::bad_expected_access`. With exceptions disabled the library cannot throw, so it ends the program instead; libc++ calls its verbose-abort handler with the message `bad_expected_access was thrown in -fno-exceptions mode`. Check the object first and use `*r`, or use `value_or`.
  • How do you build a C++ object whose construction can fail when exceptions are disabled?
    Make the constructor private and give the class a static factory, such as `static std::expected<Motor, MotorError> create(Config)`. The factory validates the inputs, returns the error if they are bad, and constructs the object only on success, so no caller ever holds a half-built object.
  • Can a header shared between builds with and without exceptions keep a throwing path?
    Yes. GCC and Clang define `__cpp_exceptions` only when exceptions are enabled, so the header can wrap the `throw` in `#if __cpp_exceptions` and fall back to returning an error or aborting. libstdc++ does the same internally with its `__try` and `__catch` macros.

  • Disabling exceptions is a standard C++ mode the compiler must support.
  • throw still compiles and just calls abort when exceptions are off.
  • std::stoi reports a bad string through its return value.
  • A constructor can return an error code to its caller.
  • std::expected::value() quietly returns a default value when empty.

Assumes C++23 for std::expected; std::from_chars and [[nodiscard]] are C++17, std::error_code C++11.