1

Supposing I have these functions defined somewhere:

std::string ws_to_s(const wchar_t*);
std::string ws_to_s(const std::wstring&);
std::wstring s_to_ws(const char*);

I wrote this class:

class runtime_error_w : public std::runtime_error {
public:
  runtime_error_w() = default;

  runtime_error_w(const wchar_t* what_arg)
    : runtime_error(ws_to_s(what_arg)) { }

  runtime_error_w(const std::wstring& what_arg)
    : runtime_error(ws_to_s(what_arg)) { }

  virtual const std::wstring what_w() const noexcept {
    return ws_to_s(what());
  }
};

So far this worked for me, but is there any problem with this approach?

Notice that what_w() returns a std::string object, not a const char*.

rodrigocfd
  • 6,450
  • 6
  • 34
  • 68
  • 3
    One potential problem is that constructing the `wstring` might throw a `bad_alloc`, which would be a problem if it happens during the handling of the original exception. – Bo Persson Dec 07 '17 at 14:56
  • Correct, but [should I worry](https://stackoverflow.com/a/9456758/6923555) about a `bad_alloc`? – rodrigocfd Dec 07 '17 at 15:20
  • Yes, you should worry about bad_alloc. Not handling an exception and letting it escape to generic uncaught exception handler, while letting RAII and stack unwinding ensure data coherence is one thing. Making code call std::terminate and potentially losing data is another. – Revolver_Ocelot Dec 07 '17 at 15:43

1 Answers1

0

Based on the comments below the question, I agree that it's a bad idea to use this class, because of a potential bad_alloc raising when constructing wstring.

rodrigocfd
  • 6,450
  • 6
  • 34
  • 68