ptal / expected

What did you expect?
113 stars 18 forks source link

Printing the what message of an exception #79

Closed salino closed 9 years ago

salino commented 9 years ago

Hi.

Please have a look at this example. It prints out

Found an error instead of the expected value.

but I would like it to output something like this:

Found an error instead of the expected value:
My error message

Is there a way to do this without having to modify the code on the client side (main ())?

Here is the full source:

#include <boost/expected/expected.hpp>

#include <iostream>
#include <stdexcept>

struct MyException : public std::runtime_error
{
  MyException ()
    : std::runtime_error ("My error message")
  {
  }
};

boost::expected <int, MyException> expected ()
{
  return 12345;
}

boost::expected <int, MyException> unexpected ()
{
  return boost::make_unexpected (MyException ());
}

int main ()
{
  try
  {
    auto a = expected ();
    auto b = unexpected ();

    std::cout << a.value () << std::endl;
    std::cout << b.value () << std::endl;
  }
  catch (const std::exception& e)
  {
    std::cerr << e.what () << std::endl;
    return 1;
  }

  return 0;
}
viboes commented 9 years ago

Have tried with

boost::expected <int>

?

salino commented 9 years ago

Sorry. I don't quite understand how this should help. Could you please elaborate?

Nevertheless, I replaced all boost::expected <int, MyException> with boost::expected <int> but now return boost::make_unexpected (); doesn't compile because it needs an input argument.

viboes commented 9 years ago

When you use expected <int, MyException> the exception throw is not MyException but bad_expected_accesswhich has "Found an error instead of the expected value."as result of a call to what().

Could you show me the compile errorr?

Have you changed

  return boost::make_unexpected (MyException ());

by

  return boost::make_unexpected ();

Why?

salino commented 9 years ago

Ah, now I understand. I first imagined I had to specify the thrown exception in the expected class. But the way it is is much cleaner.

This works as 'expected' :-)

boost::expected <int> unexpected ()
{
  return boost::make_unexpected (MyException ());
}

Thanks a lot for your help.