Allowing exception throwing in constant-evaluation

Introduction

Since adding the constexpr keyword in C++11, WG21 has gradually expanded the scope of language features for use in constant-evaluated code. At first, users couldn't even use if, else, or loops. C++14 added support for them. C++17 added support for constexpr lambdas. C++20 finally added the ability to use allocation, std::vector and std::string. These improvements have been widely appreciated, and lead to simpler code that doesn't need to work around differences between normal and constexpr C++.

The last major language feature from C++ still not present in constexpr code is the ability to throw an exception. This absence forces library authors to use more intrusive error reporting mechanisms. One example would be the use of std::expected and std::optional. Another one is the complete omission of error handling. This leaves users with long and confusing errors generated by the compiler.

Throwing exceptions in constant evaluated code is the preferred way of error reporting in the proposal adding Static Reflection for C++26. Some meta-functions can fail, and allowing them to throw will significantly simplify reflection code.

Changes

  • R1 → R2: Added library wording, new examples, implementation description, and updated impact of changes.
  • R0 → R1: Changed wording after consultation with Jens, added example to show exception can't leak via std::exception_ptr

Motivational example

consteval auto hello(std::string_view input) {
	if (input.empty()) {
		throw invalid_argument{"empty name provided"}; // BEFORE: compile-time error at throw expression site when reached
	}
	
	return concat_into_a_fixed_string("hello ",input);
}
const auto a = hello(""); // AFTER: compile-time error at call site "empty name provided"
const auto b = hello("Hana");

try {
	const auto c = hello(""); // AFTER: this exception is caught
} catch (const validation_error &) {
	// everything is fine
}

const auto d = hello("Adolph Blaine Charles David Earl Frederick Gerald Hubert Irvin John Kenneth Lloyd Martin Nero Oliver Paul Quincy Randolph Sherman Thomas Uncas Victor William Xerxes Yancy Zeus Wolfeschlegelsteinhausen­bergerdorff­welche­vor­altern­waren­gewissenhaft­schafers­wessen­schafe­waren­wohl­gepflege­und­sorgfaltigkeit­beschutzen­von­angreifen­durch­ihr­raubgierig­feinde­welche­vor­altern­zwolf­tausend­jahres­voran­die­erscheinen­van­der­erste­erdemensch­der­raumschiff­gebrauch­licht­als­sein­ursprung­von­kraft­gestart­sein­lange­fahrt­hinzwischen­sternartig­raum­auf­der­suchen­ach­die­stern­welche­gehabt­bewohnbar­planeten­kreise­drehen­sich­und­wohin­der­neu­rasse­von­verstandig­menschlichkeit­konnte­fortpflanzen­und­sich­erfreuen­an­lebenslanglich­freude­und­ruhe­mit­nicht­ein­furcht­vor­angreifen­von­anderer­intelligent­geschopfs­von­hinzwischen­sternartig­raum."); // BEFORE: compile-time error at throw expression site deep in the concat function
// AFTER: compile-time error at call site "too long name provided"

Proposed changes to wording

7.7 Constant expressions [expr.const]

(5.25) a throw-expression ([expr.throw]);, unless the lifetimes of the exception object and any implicit copies of exception object created by calls to std::current_exception() or std::rethrow_exception() end within the evaluation of E

Recommended practice: Where possible, implementations should use the thrown exception's member function named what to produce helpful diagnostics. If no such member function is available, then the implementation should emit a diagnostic containing the type and value of the thrown object. Diagnostics emitted due to an uncaught exception should include the source location of the outer-most caller, and include the source location from where the exception was thrown.]

Library wording

Note: This paper doesn't contain wording for any <stdexcept> changes as these are proposed already in P3295R0: Freestanding constexpr containers and constexpr exception types

17.9.2 Header <exception> synopsis [exception.syn]

// all freestanding
namespace std {
  class exception;
  class bad_exception;
  class nested_exception;

  using terminate_handler = void (*)();
  terminate_handler get_terminate() noexcept;
  terminate_handler set_terminate(terminate_handler f) noexcept;
  [[noreturn]] void terminate() noexcept;

  constexpr int uncaught_exceptions() noexcept;

  using exception_ptr = unspecified;

  constexpr exception_ptr current_exception() noexcept;
  [[noreturn]] constexpr void rethrow_exception(exception_ptr p);
  template<class E> constexpr exception_ptr make_exception_ptr(E e) noexcept;

  template<class T> constexpr [[noreturn]] void throw_with_nested(T&& t);
  template<class E> constexpr void rethrow_if_nested(const E& e);
}

17.9.3 Class exception [exception]

namespace std {
  class exception {
  public:
    constexpr exception() noexcept;
    constexpr exception(const exception&) noexcept;
    constexpr exception& operator=(const exception&) noexcept;
    constexpr virtual ~exception();
    constexpr virtual const char* what() const noexcept;
  };
}
constexpr exception(const exception& rhs) noexcept;
constexpr exception& operator=(const exception& rhs) noexcept;
virtual constexpr ~exception();
virtual constexpr const char* what() const noexcept;

17.9.4 Class bad_exception [bad.exception]

namespace std {namespace std {
  class bad_exception : public exception {
  public:
    // see [exception] for the specification of the special member functions
    constexpr const char* what() const noexcept override;
  };
}
virtual constexpr const char* what() const noexcept override;

17.9.6 uncaught_exceptions [uncaught.exceptions]

constexpr int uncaught_exceptions() noexcept;

17.9.7 Exception propagation [propagation]

using exception_ptr = unspecified;

(8) All member functions are marked constexpr.

constexpr exception_ptr current_exception() noexcept;
[[noreturn]] constexpr void rethrow_exception(exception_ptr p);
template<class E> exception_ptr constexpr make_exception_ptr(E e) noexcept;

17.9.8 nested_exception [except.nested]

namespace std {
  class nested_exception {
  public:
    constexpr nested_exception() noexcept;
    constexpr nested_exception(const nested_exception&) noexcept = default;
    constexpr nested_exception& operator=(const nested_exception&) noexcept = default;
    virtual constexpr ~nested_exception() = default;

    // access functions
    [[noreturn]] constexpr void rethrow_nested() const;
    constexpr exception_ptr nested_ptr() const noexcept;
  };

  template<class T> [[noreturn]] constexpr void throw_with_nested(T&& t);
  template<class E> constexpr void rethrow_if_nested(const E& e);
}
constexpr nested_exception() noexcept;
[[noreturn]] constexpr void rethrow_nested() const;
constexpr exception_ptr nested_ptr() const noexcept;
template<class T> [[noreturn]] constexpr void throw_with_nested(T&& t);
template<class E> void constexpr rethrow_if_nested(const E& e);

Implementation experience

A partial implementation in Clang is available on compiler-explorer.com. I expect it to be feature complete in time for the presentation at the St. Louis meeting.

The implementation approach is an exception slot to for throw-statements to store it in the same way as return-statements do. Every try block creates a new exception slot and try to match the appropriate catch block.

Library support is implemented via a set of new compiler builtins.

Three other compiler vendors were consulted and raised no implementability concerns.

Impact on existing code

This change doesn't break any existing code as throwing exceptions without catching them is already an error and is used by various libraries (fmt, CTHASH) to improve compile-time errors.

This proposal can make previously non-compiling code which reached a throw-statement compile by catching the thrown exception.

The intent is to keep this useful mechanism intact. The proposed wording change will only modify behavior in cases where a try/catch block is present.

Examples

Parsing date

constexpr date parse_date(std::string_view input) {
	auto [correct, year, month, day] = ctre::match<"([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})">(input);
	
	if (!correct) {
		throw incorrect_date{input};
	}
	
	return build_date(year, month, day);
}

constexpr auto birthday = parse_date("1991-07-21"); // fine
constexpr auto wrong_day = parse_date("1-2-3"); // COMPILE-TIME ERROR: provided incorrect date "1-2-3"
constexpr auto weird_day = parse_date("2023-03-29"); // COMPILE-TIME ERROR: year 2023 doesn't have a leap day

Non-transient exceptions

The current wording matches pre-P3032 wording and treats an exception basically as an allocation, and such allocation can't escape any constexpr variable initialization.

constexpr auto just_error() { 
	throw my_exception{};
}

constexpr void foo() {
	try {
		auto v = just_error(); // OK
	} catch (my_exception) {
		// do nothing
	}
	try {
		constexpr auto v = just_error(); // COMPILE-TIME ERROR: uncaught exception of type "my_exception"
	} catch (my_exception) { }
}

Exceptions must be caught

constexpr unsigned divide(unsigned n, unsigned d) {
	if (d == 0u) {
		throw invalid_argument{"division by zero"};
	}
	return n / d;
}

constexpr auto b = divide(5, 0); // BEFORE: compilation error due reaching a throw expression
// AFTER: still a compilation error but due the uncaught exception

constexpr std::optional<unsigned> checked_divide(unsigned n, unsigned d) {
	try {
		return divide(n, d);
	} catch (...) {
		return std::nullopt;
	}
}

constexpr auto a = checked_divide(5, 0); // BEFORE: compilation error
// AFTER: std::nullopt value

Constant evaluation violation behavior won't be changed

This paper doesn't propose throwing an exception for any other constant evaluation error.

constexpr unsigned read_pointer(const unsigned* p) {
	return *p;
}

constexpr unsigned try_to_ignore_ub() {
	try {
		return read_pointer(nullptr);
	} catch (...) {
		return 0;
	}
}

constexpr auto v = try_to_ignore_ub(); // UNCHANGED: error due reaching UB by dereferencing the NULL pointer (no exception is involved)

Lifetime of exception object must stay inside constant evaluation

Exception objects thrown at compile-time must be caught before leaving their respective constant-evaluated scope, and can't be stored for run-time access. This is similar to constexpr allocations, which must be deallocated before leaving their respective scopes, and any memory that's reserved at compile-time is inaccessible to run-time evaluations.

consteval auto fail() -> std::exception_ptr{
	try {
		throw failure{};
	} catch (...) {
		return std::current_exception();
	}
}

constexpr auto stored_exception = fail(); // NOT ALLOWED to store std::exception_ptr in a constexpr variable

Special thanks

To Richard Smith, Barry Revzin, Daveed Vandevoorde, Jana Machutová, Christopher Di Bella, Jens Maurer, Robert C. Seacord, Lewis Baker, David Sankel, and Guy Davidson.