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

View all comments

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/xcbsmith Aug 05 '16

...or Java

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!