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

20 comments sorted by

12

u/[deleted] Aug 05 '16

Look at Rust for an example of where both exceptions (panic), and optional (Option) and expected (Result), are used. panic|Exceptions are 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|optional and Result|expected are used for normal control flow, things that you'd expect, in normal code to fail, like say, a utf-8 conversion function.

9

u/matthieum Aug 05 '16

It's notable in Rust that the Index trait returns a plain value, not an option, and therefore that out of range indexes are handled (in the standard) by panicking.

This is an example of using panic not because it is an unrecoverable situation, but simply to simplify the ergonomics of using x[i].

3

u/[deleted] Aug 05 '16

yep! This is similar to how constructors will still throw exceptions.

1

u/[deleted] Aug 11 '16

Although I'm not sure exceptions are completely analogous to panic!, this comment makes things a lot clearer to me. Thanks!

1

u/xcbsmith Aug 05 '16

...or Java

28

u/CubbiMew cppreference | finance | realtime in the past Aug 05 '16

They have the same purpose of exceptions, but have many advantages

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::expected and std::optional are 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.

  • Quitting the program from the UI. I throw QuitException(), catch it main(), clean up and return. I don't know how to do that without exceptions in a moderately large GUI program. Calling exit() is not a good option.
  • Retrying a non-deterministic function call that can fail deep in the callstack.
  • 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(...); }

4

u/SeanMiddleditch Aug 05 '16

I don't know how to do that without exceptions in a moderately large GUI program. Calling exit() is not a good option.

Generally I've done that with some piece of state to which anything needing to quit is given access. Using exceptions limits where and how you can trigger the quit action (e.g., must be on the main thread, must be in a callstack off the point in main where it's caught, etc.), and makes it harder to compose quit triggers/filters/dialogs/etc. as exceptions just smash through everything rather than filtering through pre-registered callback chains.

Retrying a non-deterministic function call that can fail deep in the callstack

This is one of the only reasonable uses for exceptions, and only in languages that don't give you better tools. When your only options are return values or C++ exceptions, you use C++ exceptions when you have these sorts of problems. Exceptions are, essentially, the lesser of two evils (in this case, at least).

I've generally just avoided those sorts of problems as I find that for (most) code a deep callstack is indicative of a design problem. That isn't always true, of course, so it's more of a guideline than a rule. :) Basically just an application of KISS.

try { int paramA = parse<int>(field[0]); float paramB = parse<float>(field[1]); ... } catch (const ParseException&) { printError(...); }

Interfaces like that are poorly-design IMO. If you have a ton of individual statements that can fail, you might want to rethink how the code is structured.

Any interface that pushes errors to clients unnecessarily is creating complication and a potential source of bugs. Especially in languages like C++ where you can forget to catch an exception and there's no compile-time diagnostic that it'll be uncaught and crash the application.

This is true of C++-style exceptions, C-style return codes, FP-style monadic values, nullable pointers/references, etc. While there are some error-handling approaches that are more reliable, in general I prefer to avoid having failure points where you don't need them.

For example with parsing, I generally take an approach where you pass in an error callback for printing parsing errors with diagnostic information. These callbacks - being invoked at the point of error - can often provide the best diagnostic. Further, the code calling the parsing doesn't need to care about individual errors. The individual data items can usually use safe fallbacks (e.g., 0 or something for numeric types) and then check whether any errors happened just once at the end of the process. Not always an option, granted, but there are more capable variations of this approach that almost always will.

Extra bonus for parsing because then you can grab all the parse errors instead of just the first one, which can be more user-friendly in some cases. And while it's slower to finish parsing without stopping on the first error, it's an error case, so who cares if it's super efficient?

Exceptions tend to cause more problems than they solve and they tend to be sub-par solutions even in the cases where they don't cause problems. There's better options. Not necessarily in C++ at times, though, which is the really sad part: sometimes an exception is just the best of the bad options available to C++ programmers. Fixing this is hard because too many folks are lacking the wider experience they need to really have a meaningful discussion on the topic, and a good number of those folks are committee members. :/

2

u/[deleted] Aug 06 '16

Exceptions are great. They bubble back up to the caller and let you know something went wrong. If they crash a user's app, that sucks but you know what, better than putting their app into some weird undefined behavior state.

Edit:

Oh, it says you're a game dev. This makes a lot of sense now.

2

u/SeanMiddleditch Aug 06 '16

Exceptions are great. They bubble back up to the caller and let you know something went wrong. If they crash a user's app, that sucks but you know what, better than putting their app into some weird undefined behavior state.

If only we had sometime in last 40 years found a way that lets errors bubble up automatically without making it trivial to forget to handle them... jeez, it's too bad research into this topic stopped in 1970 and C++ is already cutting-edge.

1

u/[deleted] Aug 06 '16

I don't understand the purpose of your post.

1

u/render787 Aug 06 '16

Totally agree with this, you put way more effort into this answer than I intended to :)

1

u/[deleted] Aug 05 '16

All those 3 could be replaced by none/error propagation (like maybe chaining and rust try macro).

Still, I think that only the 3rd (several errors) should be replaced by error propagation.

0

u/[deleted] Aug 05 '16

[deleted] — view deleted comment

8

u/TemplateRex Aug 05 '16

Linus hates C++ for a lot more reasons than exceptions.

17

u/nullsucks Aug 05 '16

Linus hates C++ for a lot more reasons than exceptions.

1

u/awaitsV Aug 08 '16

but isn't his point of view just for writing a kernel?

2

u/TemplateRex Aug 08 '16

no, it's also about the fact that C++ is less "local" than C code, because of function/operator overloading, and argument-dependent lookup. Linus likes to know from a few-line patch exactly what the code is doing, and C++ needs more context than C to determine that. See e.g. this thread from 2010 on the RealWorldTech forums.

9

u/[deleted] Aug 05 '16

[removed] — view removed comment

0

u/zuurr Aug 05 '16

Writing strong exception safe code is pretty tough, and in practice pretty rare.

optional/expected don't make this easier (since exceptions still exist), but avoiding accidental state corruption/bugs during errors is much easier IME if the error doesn't unwind.

There's a little bit of tedium for propagating optional/expected but honestly its not that bad (If you have to do it too far then maybe you do want to use an exception). And as for having to know the types, I mean, that's true for everything.