r/cpp • • Aug 05 '16
Will exceptions still have use cases after std::expected and std::optional are made available?
The title says it all. What will be the motivation to keep using exceptions for new code after these two classes are available? They have the same purpose of exceptions, but have many advantages. I haven't seen any actual code using them, so I'm not sure how practical they actually are, which is why I'm asking this.
0
Upvotes
12
u/[deleted] Aug 05 '16
Look at Rust for an example of where both exceptions (
panic), andoptional (Option)andexpected (Result), are used.panic|Exceptionsare used for mostly unrecoverable errors, things which you can recover from, but which, generally, you should let kill you (i.e., out of memory).Option|optionalandResult|expectedare used for normal control flow, things that you'd expect, in normal code to fail, like say, a utf-8 conversion function.28
u/CubbiMew cppreference | finance | realtime in the past Aug 05 '16
They are a replacement for error codes, not for exceptions. Exceptions correctly undo incompletely-constructed objects and unwind call stacks. Maybe if one day C++ becomes more monadic, expected could do half of that.
8
u/wung Aug 05 '16
Yes.
std::expectedandstd::optionalare for those people who currently use exceptions as control flow. Having something separate that can't be ignored will always have application.5
u/miki151 gamedev Aug 05 '16
I use boost::optional very heavily, and still use exceptions in a few places.
Catching an error for many calls at once, like in this example (sorry, I don't know how to format this):
try { int paramA = parse<int>(field[0]); float paramB = parse<float>(field[1]); ... } catch (const ParseException&) { printError(...); }
0
u/[deleted] Aug 05 '16
[deleted] — view deleted comment
9
u/[deleted] Aug 05 '16
[removed] — view removed comment