C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Try-catch declaration

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Wed, 22 Nov 2023 16:11:08 +0000
On Wed, 22 Nov 2023 at 14:13, sasho648 via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> It's UB - there is nothing else to add about it - don't know where you are
> inheriting all this.
>

Then it's just a big footgun and far too easy to misuse.

Use std::expected or std::optional instead.

Assuming we get optional<T&> and then can have expected<T&, E>, you can
wrap your func() to handle the exception:

std::expected<T&, int> wrapped_func() {
  try {
    return func();
  } catch (...) {
    return std::unexpected(-1);
  }
}

Then you can do:

if (auto r = wrapped_func())
  ...

Received on 2023-11-22 16:11:24