C++ Logo

std-proposals

Advanced search

Re: [std-proposals] RTTI in current_exception

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, 10 Jan 2023 12:02:33 -0500
On Tue, Jan 10, 2023 at 11:03 AM Thiago Macieira via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> On Tuesday, 10 January 2023 06:40:35 PST Jason McKesson via Std-Proposals
> wrote:
> > I disagree with this.
> >
> > `std::exception` is not a good type. The only actual functionality it
> > provides is a virtual interface for getting a `char const*`. Which
> > then locks any user into using that *specific* interface for
> > retrieving a description of the error. If I want to get the string as
> > a `string_view` or `span<char const*>` so that I can embed NUL
> > characters, I'm out of luck. Or better yet, maybe I want to use a
> > `char8_t const*` so everyone knows its UTF-8 encoded.
>
> A text description has no business including NUL.
>
> In any case, that's what happens when things get designed in the late 80s and
> early 90s. Today, a green-field design would indeed use string_view.
>
> And std::string_view is UTF-8 if you put UTF-8 in.
>
> > I see no reason why we should in any way discourage library writers
> > from using their own exception base class that provides the base
> > functionality appropriate to their library.
>
> They're welcome to do that inside their own libraries. C++ allows it. Someone
> else in this thread said they're throwing enums. It's not for performance they
> do it, though.
>
> But if you want users to catch exceptions, PLEASE derive from std::exception.
> You can create your own base that adds stuff and you can even not have a
> meaningful what().

Then what's the point of deriving from `std::exception`? What is the
difference between the following:

```
catch(std::exception &no_meaningful_info)
{
  auto nothing = no_meaningful_info.what();
  log(nothing); //Produces nothing helpful.
}
```

```
catch(...)
{
  log("Unknown exception.");
}
```

If you are making an exception class derived from `std::exception`,
then the expectation is that it *does* provide meaningful interfaces.
If your exception class can't, or doesn't want to, conform to
`std::exception`, then it shouldn't have to and we shouldn't encourage
people to do so.

We should not pretend that `catch(std::exception&)` is intended to be
a catch-all. The "catch-all" in C++ is spelled `catch(...)`.

Each library can have their own base exception classes that they emit.
And there is nothing wrong with that. If the user wants to catch them
and interface with those types, that's fine. If the user wants to just
treat them as unknown exceptions via `catch(...)` and do some default
action, that's fine too. It's their choice.

But we gain nothing by telling people to derive from `std::exception`
even when they don't actually make that interface meaningful.

Received on 2023-01-10 17:02:39