C++ Logo

std-proposals

Advanced search

Re: Middle ground between "return" and exceptions?

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Mon, 14 Sep 2020 16:53:38 -0400
On Mon, Sep 14, 2020 at 3:21 PM Dmitry Dmitry via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>>>
>>>
>> However, what you want is already possible in Standard C++:
>>
>> std::optional<std::string> FindUsersCity() {
>> try {
>> std::optional<ContactsServer> contacts = GetOrOpenContactsServerConnection();
>> std::optional<UserId> uid = contacts.value().GetUserId(); // throw bad_optional_access on empty
>> std::optional<GeoServer> geo = GetOrOpenGeoServerConnection();
>> std::optional<Location> uloc = geo.value().GetLocation(uid.value()); // throw bad_optional_access on empty
>> return uloc.value().GetCityName();
>> } catch (const std::bad_optional_access&) {
>> return std::nullopt;
>> }
>> }
>>
>
> If you want the same level of flexibility as with returns (and you usually want, because sometimes you need to be more specific and capture some context/explanation),

Then the functions detecting the error situation should be the ones
throwing the error, rather than relying on a generic
`bad_optional_access` error.

If those functions emitted an `expected<T, error>`, then the `error`
would contain adequate context information. And therefore, if an
exception gets thrown, the catcher will at least have the error code
or whatever is needed to provide context.

Received on 2020-09-14 15:53:51