Date: Fri, 12 Dec 2025 14:36:00 +0300
On 12 Dec 2025 14:03, Jonathan Wakely via Std-Proposals wrote:
>
> On Fri, 12 Dec 2025 at 10:59, Jonathan Wakely <cxx_at_[hidden]
> <mailto:cxx_at_[hidden]>> wrote:
>
> For case B you are much better off capturing the data in the
> exception object directly, not formatting it as a string.
>
> i.e. instead of:
>
> throw network_error("connection failed (with layer = {}, protocol = {},
> local_endpoint = {}, remote_endpoint = {}, error_code = {}, reason =
> \"{}\", status = \"{}\"", layer, proto, lep, rep, ec, why, status);
>
> you should do:
>
> throw network_error("connection failed", layer, proto, lep, rep, ec,
> why, status);
>
> The exception type should store those values and provide getters to
> access those values later. It can also use std::format internally to
> create a string that is stored and returned from network_error::what()
> (maybe by passing that string to a std::runtime_error base class, if it
> derives from that).
A better design, that is unfortunately rarely followed, is to perform
string formatting lazily in what() instead of when constructing an
exception. With a fallback in the unlikely case when the formatting
fails. This way the formatting won't be wasted if the formatted message
is never requested by the caller. I think I saw this design
recommendation in Boost somewhere, but I can't find where.
>
> On Fri, 12 Dec 2025 at 10:59, Jonathan Wakely <cxx_at_[hidden]
> <mailto:cxx_at_[hidden]>> wrote:
>
> For case B you are much better off capturing the data in the
> exception object directly, not formatting it as a string.
>
> i.e. instead of:
>
> throw network_error("connection failed (with layer = {}, protocol = {},
> local_endpoint = {}, remote_endpoint = {}, error_code = {}, reason =
> \"{}\", status = \"{}\"", layer, proto, lep, rep, ec, why, status);
>
> you should do:
>
> throw network_error("connection failed", layer, proto, lep, rep, ec,
> why, status);
>
> The exception type should store those values and provide getters to
> access those values later. It can also use std::format internally to
> create a string that is stored and returned from network_error::what()
> (maybe by passing that string to a std::runtime_error base class, if it
> derives from that).
A better design, that is unfortunately rarely followed, is to perform
string formatting lazily in what() instead of when constructing an
exception. With a fallback in the unlikely case when the formatting
fails. This way the formatting won't be wasted if the formatted message
is never requested by the caller. I think I saw this design
recommendation in Boost somewhere, but I can't find where.
Received on 2025-12-12 11:36:07
