We are porting our codebase from Objective-C to C++ 11. In Obj-C, most every object inherits from NSObject and then you only pass pointers around. This is very convenient for errors, as you can usually let the caller know there is no object by simply returning nil (null). While porting to C++, I've begun to run into the fact that there is no real parallel (or at least it would be ugly to do it that way with memory management). Do libraries usually simply throw an exception up to the caller even for non-critical errors? how do you know what layer is proper to catch it on? Is it more kosher to pass an error variable by reference?
Asked
Active
Viewed 186 times
0
-
C++17 has `std::optional`. If you want you can implement it in C++11. – user202729 Jan 16 '18 at 04:34
-
So if it's non-critical, it's not really an error, it's expected behavior. Consider a file stream, after assigning it to a file it's possible to check if the stream is `bad` by looking at the flags. – user202729 Jan 16 '18 at 04:35
-
Also, exceptions are often slower to handle, if that's not really "exception" then don't make it to be. – user202729 Jan 16 '18 at 04:36
-
More thinking of examples like string parsers and manipulators. If something is not in the exact right format, coming from Obj-C, it seems over the top to be throwing exceptions. That is why I ask the question. – David Jan 16 '18 at 04:42
-
[Related](https://stackoverflow.com/q/3157098), potentially duplicate. – user202729 Jan 16 '18 at 04:44
-
I do not feel this is a duplicate. This does not really relate to error codes. I want to return an object. If something goes wrong, how do I let the app know the "correct" way. I – David Jan 16 '18 at 04:53
-
So, as suggested, you return a `Expected – user202729 Jan 16 '18 at 04:54
1 Answers
1
std::optional
is a nice way to do this (as pointed out by user202729 in his comment).
If you don't have C++17 support you can use boost::optional
which is pretty much the same as C++17's std::optional.
If you also want to return informational data in case of error (e. g. an error string) you should take a look at "expected". It neither made it into STL yet nor into boost but there is a proposal for STL already: https://github.com/viboes/std-make/blob/master/doc/proposal/expected/DXXXXR0_expected.pdf and there are some independent implementations available, e. g.: https://github.com/martinmoene/expected-lite

Lorenz Zhao
- 242
- 1
- 11